<?php

namespace app\api\controller;

use app\api\model\Attention;
use app\api\model\AuthImg;
use app\api\model\Chaoe;
use app\api\model\Code;
use app\api\model\ConfigPersonal;
use app\api\model\GradeCharm;
use app\api\model\GradeDefend;
use app\api\model\GradeNoble;
use app\api\model\GradeStar;
use app\api\model\ImgBurn;
use app\api\model\Labels;
use app\api\model\LabelsUser;
use app\api\model\Pingjia;
use app\api\model\Reg as RegModel;
use app\api\model\ReportUser;
use app\api\model\Feedback;
use app\api\model\SeeRecord;
use app\api\model\UserDefend;
use app\api\model\UserImg;
use app\api\model\UserZan;
use app\api\model\VipNum;
use app\api\model\ConfigSystem as Config;
use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords as Income;
use think\Request;
use think\Db;
use app\api\model\Blacklist;
use app\api\model\UserMaterialVerify;
use app\api\model\User as UserModel;
use app\api\model\Privatechat;
use app\api\model\UserIntimate;
use app\service\UserIntimate as UserIntimateService;
use app\api\model\Cluster;
use app\api\model\BeautyImage;
use app\api\model\Task;
use app\api\model\RankingRecords;
use app\service\UserWarn;
use app\api\model\UserDeedLimit;
use app\api\model\UserPunish;
// use app\api\model\UserProfile;
use think\Cache;
use app\service\FaceAuth;
use Vectorface\Whip\Whip;
use app\utils\IpInfoUtils;
use GatewayClient\Gateway;

class User extends Common
{
    public $regnewtime = null;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->regnewtime = strtotime('2012-09-22');
    }
    public function index(Request $request = null, $avtive = 0, $entertainment = 0)
    {
        $where = "entertainment = ".$entertainment." and entertainment !=1 and shouyi < 100000 and proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1 and age >= 18 and quality != 1";

        $config = Config::where(['category' => ['in', ['kefu', 'user']]])->column('title, content');
        
        if (isset($this->params['user_id']) && $this->params['user_id']) {
            $response = UserModel::checkLogin($this->params['user_id']);


            $result = $response->getData();

            if ($result['code'] == 400) {
                return $response;
            }

            $this->member = $result['user'];
            if ($this->member['age'] < 18 || $this->member['entertainment'] == 1) {
                return $this->pass([], 'result');
            }

            $login = 1;

            if($config['id'] == $this->params['user_id']){
                $where = "proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1";
            }
        } else {
            $login = 0;

            /*if (in_array($nav, [2,3])) {
                return $this->return['user.error.expired'];
            }*/
        }

        $today_start = date('Y-m-d H:i:s', strtotime(date('Y-m-d')));



        if ($login) {
            $blacklist = Blacklist::lists($this->member['id'], false, true);
            if (strtotime($this->member['register_datetime']) > strtotime($config['user_list_hide'])) {
                return $this->pass([]);
            }
            if ($blacklist) {
                $blacklist[] = $config['id'];
            } else {
                $blacklist = [$config['id']];
            }
            
            if ($request->param('attention')) {
                $attention = Attention::lists($this->member['id'], false, true);
                
                $attention_str = implode(',', array_diff($attention, $blacklist));
                $attention_str = $attention_str ?: 0;
                $where .= " and id in ($attention_str)";
            } else {
                $blacklist_str = implode(',', $blacklist);

                // 标签筛选
                if ($request->param('labels')) {
                    $label_ids = explode(',', $request->param('labels'));

                    $user_ids = LabelsUser::where(['types' => 1, 'label_id' => ['in', $label_ids]])->column('user_id');

                    $label_users = implode(',', array_diff($user_ids, $blacklist));
                    $label_users = $label_users ?: 0;

                    $where .= " and id in ($label_users)";
                } else {
                    $where .= " and id not in ($blacklist_str)";
                }
            }

            if ($request->param('hot') && !$request->param('age')) {
                if($this->member['age']){
                    if($this->member['sex'] == '男'){
                        $where .= " and age <= " . $this->member['age'];
                    }else{
                        $where .= " and age <= " . ($this->member['age'] + 10);
                    }
                }
            }
        }


        if ($request->param('id')) {
            $where .= " and id = " . $request->param('id');
        }

        if ($request->param('age')) {
            if (stripos($request->param('age'), ',')) {
                $age = explode(',', $request->param('age'));
                $where .= " and (age >= " . $age[0] . " and age <= " . ($age[1]?$age[1]:99) . ")";
            } else {
                $where .= " and age > " . $request->param('age');
            }
        }

        if ($request->param('stature')) {
            if (stripos($request->param('stature'), ',')) {
                $stature = explode(',', $request->param('stature'));
                $where .= " and (stature >= " . $stature[0] . " && stature <= " . $stature[1] . ")";
            } else {
                $where .= " and stature > " . $request->param('stature');
            }
        }

        $param_sex = $request->param('sex');
        if ($login && !$param_sex) {
            if ($config['id'] != $this->member['id']) {
                $sex = $this->member['sex'] == '男' ? '女' : '男';
                $where .= " and sex = '$sex'";
            }
            // if ($sex == '男') {
            //     $where .= " and yqr = ''";
            // }
            // if (isset($sex) && $sex == '女'){
            //     $where .= " and register_datetime < '$today_start'";
            // }else{
            // }
        } else {
            if ($param_sex && in_array($param_sex, ['男','女'])) {
                $sex = $param_sex;

                $where .= " and sex = '$sex'";

                if ($sex == '男') {
                    // $where .= " and yqr = ''";
                    $overtopup = Db::name('user_data')->where(['topup'=>['>=', 20000]])->column('user_id');
                    if(sizeof($overtopup)){
                        $where .= " and id not in (" . implode(',', $overtopup) . ")";
                    }
                }
            } else {
                $where .= " and sex = '女'";
            }

        }

        if ($request->param('name')) {
            $where .= " and (name LIKE '%" . $request->param('name') . "%' or id LIKE '%" . $request->param('name') . "%')";
        }

        if ($request->param('city')) {
            $where .= " and (city LIKE '" . $request->param('city') . "%' or notlimit_city <> 0)";
        }

        if ($request->param('occupation')) {
            $where .= " and (occupation = '" . $request->param('occupation') . "')";
        }

        if ($avtive) {
            if ($avtive == 1) {
                $where .= " and (is_online = 1)";
            } else if ($avtive == 2) {
                $where .= " and (is_online = 1 or last_login_datetime >= '".date('Y-m-d H:i:s', strtotime('-72 hour'))."')";
            } else if ($avtive == 3) {
                $where .= " and (is_online = 1 or last_login_datetime >= '".date('Y-m-d H:i:s', strtotime('-168 hour'))."')";
            }
        }



        if ($request->param('vip')) {
            $where .= " and vip_end_datetime > '" . date('Y-m-d H:i:s') . "'";
        }

        if ($request->param('nvshen')) {
            $where .= " and nvshen = 1";
        }

        if (!$request->param('id') && !$request->param('sex')) {
            $where .= " and home_hidden = 0";
        }

        if ($request->param('is_identity_authentication')) {
            $where .= " and is_identity_authentication = 2";
        }

        if ($request->param('star')) {
            $gradeStar = GradeStar::where(['grade' => $this->params['star']])->find();

            if ($gradeStar) {
                $where .= " and (score >= " . $gradeStar->min . " and score <= " . $gradeStar->max . ")";
            }
        }

        /*if ($request->param('hot') && $this->member['city']) {
            $where .= " and (is_recommend = 1 or city like '%" . $this->member['city'] . "%')";
        }*/

        $order = '';

        if ($request->param('online')) {
            $order = "is_online desc, ";
        }

        $page = $request->param('page') ?: 0;
        $pagesize = $request->param('pagesize') ?: 10;

        if($page == 0){
            Cache::rm($this->params['user_id'] . 'indexskip');
        }
        $indexskip = 0;
        if ($request->param('hot')) {       // 推荐
            if (!$request->param('name') && !$request->param('city') && !$request->param('occupation') && !$request->param('active')) {
                $indexskip = Cache::get($this->params['user_id'] . 'indexskip');
                if(!$indexskip){
                    $indexskip = rand(0,99);
                    Cache::set($this->params['user_id'] . 'indexskip', $indexskip);
                }
            }
            //$order .= 'is_recommend desc, sort desc, role asc, is_online desc, last_login_datetime desc';
            $order .= 'is_online desc, is_recommend desc, activeval desc, case when shouyi<1000 then 0 else 1 end, last_login_datetime desc';
        } elseif($request->param('nearby')){
            // return $this->pass([]);
            $order .= "distance asc, activeval desc, case when shouyi<1000 then 0 else 1 end";
            $where .= ' and city ="' . $this->member['city'] . '"';
        } elseif($request->param('new')){
            return $this->pass([]);
            $where .= ' and register_datetime >="' . date('Y-m-d H:i:s', time() - 7 * 24 * 60 * 60) . '"';
            $order = "id desc";
        } else {
            $order .= "sort desc, activeval desc, case when shouyi<1000 then 0 else 1 end, is_online desc, distance asc";
        }


        // 今日缘分
        if ($request->param('fate')) {
            // return $this->pass([], 'result');

            //$where .= " and is_online = 1 and role = 0 having distance <= 100000";
            $where .= " and role = 0 and yqr = '' and last_login_time>".(time() - 3 * 86400);
            // $order = 'rand()';
            $pagesize = 6;

            if($login){

                $search_uid = $this->member['id'];
                // $sql = "select * from user_intimate where (FIND_IN_SET($search_uid, couple_a) or FIND_IN_SET($search_uid, couple_b)) and intimate > 100";
                $sql = "(SELECT * from user_intimate where couple_a like '$search_uid,%' and intimate >= 100) union (SELECT * from user_intimate where couple_b like '$search_uid,%' and intimate >= 100)";
                $userIntimate = Db::query($sql);
    
                if ($userIntimate) {
                    $intimate_uids = [];
                    foreach ($userIntimate as $key => $item) {
                        $intimate_uid = explode(',', $item['couple_a']);
            
                        $intimate_uids[] = $intimate_uid[0] == $search_uid ? $intimate_uid[1] : $intimate_uid[0];
                    }
        
                    $intimate_uids = array_merge($blacklist, $intimate_uids);
                    
                    $where .= ' and id not in ('.implode(',',$intimate_uids).')';
                }

                $indexskip = rand(0,99);
                if($this->member['sex'] == '女'){
                    $age = $this->member['age'] > 0 ? $this->member['age'] : 0;
                    if($this->member['shouyi'] > 1000){
                        $order = "is_online desc, activeval desc";
                    }else{
                        $order = "is_online desc, case when volley>200 then 0 else 1 end, activeval desc";
                        $indexskip = rand(0,50);
                    }
                }
            }
        }

        // 语音匹、视频匹配
        if ($request->param('video_mate') || $request->param('voice_mate')) {
            if ($this->member['age']) {
                $where .= " and (age > " . ($this->member['age'] - 20) . " and age < " . ($this->member['age'] + 20) . ")";
            }

            $ids = Db::name('records_mate')->where(['user_id' => $this->member['id']])->column('to_user');

            /*$field = $request->param('video_mate') ? 'video_switch' : 'voice_switch';

            $ids = ConfigPersonal::where([$field => 0])->column('user_id');*/

            if ($ids) {
                $ids = '(' . implode(',', $ids) . ')';
                $where .= ' and id not in ' . $ids;
            }

            //$where .= " and is_online = 1 having distance <= 100000";
            $where .= " and is_online = 1 ";
            $indexskip = 0;
            $page = 0;
            $pagesize = 1;
            if ($request->param('fate')) {
                $order = 'quality desc, last_login_datetime desc';
            } else if ($this->member['sex'] == '男') {
                $order = 'attestation desc, role asc, quality desc, charm_value desc, score desc';
            } else {
                $order = 'attestation desc, role asc, quality desc, noble_grade desc, volley desc';
            }

            if ($request->param('voice_mate')) {
                // 任务
                Task::finish('voice_mate', $this->member['id']);
            } else if ($request->param('video_mate')) {
                // 任务
                Task::finish('video_mate', $this->member['id']);
            }
        }

        if ($request->param('appointment')) {
            $ids = ConfigPersonal::where(['video_switch' => 1])->column('user_id');

            $ids = $ids ? '(' . implode(',', $ids) . ')' : '(0)';
            $where .= ' and is_online = 1 and id in' . $ids;
        }

        for ($i = 0; $i < 1; $i++) {
            $distance_sql = distance($this->params['latitude'], $this->params['longitude']);

            $field = 'id user_id, name user_name, head_100 user_head, sex user_sex, age user_age, city,
                img_auth, is_online, is_identity_authentication, last_login_datetime, nvshen, hide_online_time,
                noble_grade, noble_time, hide_distance, kejian, xuni_discount, notlimit_city, role, voice,
                voice_time, voice_auth, realname_auth, register_datetime, yqr, real_avatar, occupation, auth_tag, entertainment,self_slogan';

            $sql = "select $field, $distance_sql from user where $where order by $order limit " . ($page * $pagesize + $indexskip) . ", $pagesize";
            // var_dump($sql);exit;
            $data = Db::query($sql);

            if ($data) {
                if ($page && ($request->param('hot') || $request->param('nearby')) && count($data) < $pagesize) {
                    $page = 0;
                    $i = -1;
                } else {
                    if ($request->param('video_mate') || $request->param('voice_mate')) {
                        Db::name('records_mate')->insert(['user_id' => $this->member['id'], 'to_user' => $data[0]['user_id'], 'create_time' => time()]);
                    }

                    $gradeNoble = GradeNoble::where(['id' => ['gt', 0]])->cache(86400)->column('id, icon, circle');

                    $ids = array_column($data, 'user_id');
                    //$personals = Db::name('config_personal')->where(['user_id' => ['in', $ids]])->column('user_id, id, hide_distance');

                    $user_labels = Labels::lists($ids);
    
                    $car_ids = Db::name('user_car')->where(['user_id' => ['in', $ids], 'expire' => ['gt', time()], 'is_select' => 1])->column('user_id, car_id');
                    if ($car_ids) {
                        $car_covers = Db::name('car')->where(['id' => ['in', $car_ids]])->cache(86400)->column('id, cover');
                    } else {
                        $car_covers = [];
                    }
    
                    $photo_uids = [];
                    $photos = [];
                    foreach ($data as $key => $item) {
                        if ($item['voice_auth'] != 2 || !$item['voice']|| !$item['voice_time']) {
                            $photo_uids[] = $item['user_id'];
                        }
                    }
                    
                    if ($photo_uids) {
                        $userImgs = UserImg::where(['types' => 1, 'user_id' => ['in', $photo_uids], 'burn' => 0, 'packet' => 0, 'is_auth' => 0, 'is_avatar' => 0, 'status' => 1])->order('id desc')->cache(7200)->select();
                        $photos = [];
                        foreach ($userImgs as $img) {
                            if (!isset($photos[$img['user_id']]) || count($photos[$img['user_id']]) < 4) {
                                $pic = json_decode($img['picthumb'], true);
                                if (isset($pic[0])) {
                                    $photos[$img['user_id']][] = changeUrl($pic[0]);
                                }
                            }
                        }
                    }
                    $timenow = time();
                    foreach ($data as $key => $item) {
                        if (!$request->param('video_mate') && !$request->param('voice_mate') && !$request->param('fate')) {
                            if (isset($car_ids[$item['user_id']]) && isset($car_covers[$car_ids[$item['user_id']]])) {
                                $data[$key]['car_cover'] = changeUrl($car_covers[$car_ids[$item['user_id']]]);
                            } else {
                                $data[$key]['car_cover'] = '';
                            }
                        }

                        $data[$key]['is_vip'] = $item['noble_grade'] && $item['noble_time'] > time() ? 1 : 0;
                        $data[$key]['is_new'] = (strtotime($item['register_datetime']) + 86400) > time() ? 1 : 0;

                        if ($item['hide_distance']) {
                            $data[$key]['user_distance'] = '保密';
                        } else {
                            $distance = $item['xuni_discount'] + 0 ? $item['xuni_discount'] : $item['distance'];
                            $data[$key]['user_distance'] = $distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm';
                        }

                        if (!$request->param('nearby')) {
                            $data[$key]['user_distance'] = '';
                        }

                        /*if (isset($personals[$item['user_id']]['hide_distance']) && $personals[$item['user_id']]['hide_distance']) {
                            $data[$key]['city'] = '';
                        } else {
                            $data[$key]['city'] = $login && $item['notlimit_city'] ? $this->member['city'] : $item['city'];
                        }

                        if ($config['hide_city'] && $item['user_sex'] == '女') {
                            $data[$key]['city'] = '';
                        }*/


                        if ($item['is_online'] == 0) {
                            if ($timenow - 3*86400 < strtotime($item['last_login_datetime'])) {
                                $data[$key]['is_online'] = 1;
                            }
                        }
                        $data[$key]['last_login_datetime'] = changeTime($data[$key]);

                        if ($item['noble_grade'] && $item['noble_time'] > time()) {
                            $data[$key]['noble_icon'] = $gradeNoble[$item['noble_grade']] ? $gradeNoble[$item['noble_grade']]['icon'] : '';
                            $data[$key]['noble_circle'] = $gradeNoble[$item['noble_grade']] ? $gradeNoble[$item['noble_grade']]['circle'] : '';
                        } else {
                            $data[$key]['noble_icon'] = '';
                            $data[$key]['noble_circle'] = '';
                        }

                        // if ($item['voice_auth'] != 2) {
                            $data[$key]['voice'] = '';
                        // }
    
                        if ($item['voice_auth'] != 2 || !$item['voice']|| !$item['voice_time']) {
                            $data[$key]['photos'] = $photos[$item['user_id']] ?? [];
                        } else {
                            $data[$key]['photos'] = [];
                        }

                        $labels = $user_labels[$item['user_id']] ?? [];
                        $data[$key]['labels'] = array_slice($labels, 0, 5);

                        unset($data[$key]['img_auth'], $data[$key]['xuni_discount'],$data[$key]['noble_grade'], $data[$key]['noble_time'],
                            $data[$key]['notlimit_city'], $data[$key]['distance'], $data[$key]['register_datetime'], $data[$key]['role'],
                            $data[$key]['hide_distance'], $data[$key]['hide_online_time'], $data[$key]['voice_auth']);

                        // if(($this->member['yqr'] && $this->member['sex'] == '男') || strtotime($this->member['register_datetime']) < $this->regnewtime){
                        //     $data[$key]['city'] = '';
                        // }
                        // unset($data[$key]['user_distance']);
                        unset($data[$key]['yqr']);
                        // $data[$key]['is_online'] = 0;
                    }
                }
            } else {
                $data = [];

                if ($page && ($request->param('hot') || $request->param('nearby'))) {
                    $page = 0;
                    $i = -1;
                } else {
                    if ($request->param('video_mate') || $request->param('voice_mate')) {
                        Db::name('records_mate')->where(['user_id' => $this->member['id']])->delete();
                    }
                }
            }
        }

        return $this->pass($data, 'result');
    }

    public function search(Request $request = null, $entertainment = 0)
    {

        $limit = Db::name('search_limit')->where(['user_id'=>$this->member['id']])->find();

        $where = "proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1";

        if (!$entertainment) {
            $where = "entertainment !=1 and shouyi < 100000 and proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1 and age >= 18 and quality != 1";
        }


        if($limit){
            if (!$entertainment) {
                return $this->pass([]);
            }
            $where .= ' and entertainment = 1';
        }


        $config = Config::where(['category' => ['in', ['kefu', 'user']]])->column('title, content');


        $where .= " and id <> " . $config['id'];

        $page = $request->param('page') ?: 0;
        $pagesize = $request->param('pagesize') ?: 10;

        if ($config['id'] == $this->member['id']) {
            $where = "delete_time = 0";
        } else if (!$entertainment) {
            $sex = $this->member['sex'] == '男' ? '女' : '男';
            $where .= " and sex = '$sex'";
        }

        if ($request->param('name')) {
            $where .= " and (name LIKE '%" . $request->param('name') . "%' or id LIKE '%" . $request->param('name') . "%')";
        }
        
        // $limitdatetime = '2023-04-15 00:00:00';
        // $limittime = strtotime($limitdatetime);
        // if (strtotime($this->member['register_datetime']) >= $limittime) {
        //     $where .= " and register_datetime >= " . $limitdatetime . "'";
        // } else {
        //     $where .= " and register_datetime < '" . $limitdatetime . "'";
        // }


        $distance_sql = distance($this->params['latitude'], $this->params['longitude']);
        $field = 'id user_id, name user_name, head_100 user_head, sex user_sex, age user_age, city, occupation,
            img_auth, is_online, is_identity_authentication, last_login_datetime, nvshen, hide_online_time,
            noble_grade, noble_time, hide_distance, kejian, xuni_discount, notlimit_city, role, voice,
            voice_time, voice_auth, stature, realname_auth, register_datetime, yqr, real_avatar, auth_tag, entertainment, self_slogan';
        $sql = "select $field, $distance_sql from user where $where order by last_login_datetime desc limit " . ($page * $pagesize) . ", $pagesize";
        // var_dump($sql);exit;
        $data = Db::query($sql);

        if ($request->param('video_mate') || $request->param('voice_mate')) {
            Db::name('records_mate')->insert(['user_id' => $this->member['id'], 'to_user' => $data[0]['user_id'], 'create_time' => time()]);
        }

        $gradeNoble = GradeNoble::where(['id' => ['gt', 0]])->cache(86400)->column('id, icon, circle');

        $ids = array_column($data, 'user_id');
        //$personals = Db::name('config_personal')->where(['user_id' => ['in', $ids]])->column('user_id, id, hide_distance');

        $user_labels = Labels::lists($ids);

        $car_ids = Db::name('user_car')->where(['user_id' => ['in', $ids], 'expire' => ['gt', time()], 'is_select' => 1])->column('user_id, car_id');
        if ($car_ids) {
            $car_covers = Db::name('car')->where(['id' => ['in', $car_ids]])->cache(86400)->column('id, cover');
        } else {
            $car_covers = [];
        }

        $photo_uids = [];
        $photos = [];
        foreach ($data as $key => $item) {
            if ($item['voice_auth'] != 2 || !$item['voice']|| !$item['voice_time']) {
                $photo_uids[] = $item['user_id'];
            }
        }
        
        if ($photo_uids) {
            $userImgs = UserImg::where(['types' => 1, 'user_id' => ['in', $photo_uids], 'burn' => 0, 'packet' => 0, 'is_auth' => 0, 'is_avatar' => 0, 'status' => 1])->order('id desc')->cache(7200)->select();
            $photos = [];
            foreach ($userImgs as $img) {
                if (!isset($photos[$img['user_id']]) || count($photos[$img['user_id']]) < 4) {
                    $pic = json_decode($img['picthumb'], true);
                    if (isset($pic[0])) {
                        $photos[$img['user_id']][] = changeUrl($pic[0]);
                    }
                }
            }
        }
        $timenow = time();
        foreach ($data as $key => $item) {

            $data[$key]['is_vip'] = $item['noble_grade'] && $item['noble_time'] > time() ? 1 : 0;
            $data[$key]['is_new'] = (strtotime($item['register_datetime']) + 86400) > time() ? 1 : 0;

            if ($item['hide_distance']) {
                $data[$key]['user_distance'] = '保密';
            } else {
                $distance = $item['xuni_discount'] + 0 ? $item['xuni_discount'] : $item['distance'];
                $data[$key]['user_distance'] = $distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm';
            }


            if ($item['is_online'] == 0) {
                if ($timenow - 3*86400 < strtotime($item['last_login_datetime'])) {
                    $data[$key]['is_online'] = 1;
                }
            }
            $data[$key]['last_login_datetime'] = changeTime($data[$key]);

            if ($item['noble_grade'] && $item['noble_time'] > time()) {
                $data[$key]['noble_icon'] = $gradeNoble[$item['noble_grade']] ? $gradeNoble[$item['noble_grade']]['icon'] : '';
                $data[$key]['noble_circle'] = $gradeNoble[$item['noble_grade']] ? $gradeNoble[$item['noble_grade']]['circle'] : '';
            } else {
                $data[$key]['noble_icon'] = '';
                $data[$key]['noble_circle'] = '';
            }

            if ($item['voice_auth'] != 2) {
                $data[$key]['voice'] = '';
            }

            if ($item['voice_auth'] != 2 || !$item['voice']|| !$item['voice_time']) {
                $data[$key]['photos'] = $photos[$item['user_id']] ?? [];
            } else {
                $data[$key]['photos'] = [];
            }

            $labels = $user_labels[$item['user_id']] ?? [];
            $data[$key]['labels'] = array_slice($labels, 0, 5);

            unset($data[$key]['img_auth'], $data[$key]['xuni_discount'],$data[$key]['noble_grade'], $data[$key]['noble_time'],
                $data[$key]['notlimit_city'], $data[$key]['distance'], $data[$key]['register_datetime'], $data[$key]['role'],
                $data[$key]['hide_online_time'], $data[$key]['voice_auth']);
            //  $data[$key]['hide_distance'],
            // if(isset($this->params['user_id']) && $this->params['user_id'] && (($this->member['yqr'] && $this->member['sex'] == '男') || strtotime($this->member['register_datetime']) < $this->regnewtime)){
            //     $data[$key]['city'] = '';
            // }
            unset($data[$key]['user_distance']);
            unset($data[$key]['yqr']);
        }

        return $this->pass($data, 'result');
    }

    public function info(Request $request = null)
    {
        $id = $request->param('to_user');
        $user_id = $request->param('user_id');

        if (!$this->member || $this->member['reg']==0) {
            return $this->miss('请登录',402);
        }

        $distance_sql = distance($request->param('latitude'), $request->param('longitude'));


        $table = 'user';
        if ($user_id > 30000000) {
            $database9 = getenv('DB9_DATABASE');
            $table = $database9 . '.user';
        }

        $field = 'id, name, head_100, head_300, head_portrait, sex, phone, age, city, offten_city, occupation, slogan, self_slogan, 
                constellation, img_auth, is_online, is_identity_authentication, hide_online_time, nvshen, last_login_datetime, 
                hide_distance, kejian, xuni_discount, notlimit_city, role, img_auth, photo_price, stature, 
                weight, wxcount, qq, lianmai_limit, paypwd, shoushi, hide_search, volley, zhifucount, zhifuname, proxy, 
                invite_count, vip_num, vip_count, shouyi, dy_program, dy_conditions, yqm send_code, 
                score, tycoon, charm_value, zan, angel, video, cover, voice, voice_auth, voice_zan, noble_grade, noble_time, 
                attention, following, friend, birthday, monthly_salary, education_background, emotion, realname_auth, register_datetime, 
                line_price,heart, zhaohu_time, school_of_graduation, live_status, is_house_purchase, is_car_purchase, tags, speaker, 
                through_membership, self_images, voice_time, free_chat, free_voice, free_video, yqr, is_banned, banned_end_time, wechat, wechat_name, real_avatar, reg, entertainment, auth_tag, income_auth, marry_auth, is_education_authentication, house_auth, car_auth';

        $sql = "select $field, $distance_sql from $table where id = $user_id and delete_time = 0";

        $data = Db::query($sql);
        // var_dump($data);exit;

        if ($data) {
            $data = $data[0];
    
            if (!$id && (strtotime($data['last_login_datetime']) + 86400 * 3) < time()) {
                UserModel::update(['id' => $user_id, 'is_online' => 0]);
                return $this->return['user.error.afreshLogin'];
            }

            $config = Config::where(['category' => ['in', ['user', 'kefu', 'defend', 'invite', 'family', 'sayhi', 'two_way_charge']]])->cache(3600)->column('title, content');

            $kefu = intval($config['id']);
    
            $data['configPersonal'] = $configPersonal = Db::name('config_personal')->where(['user_id' => $user_id])->find();

            if ($data['configPersonal']) {
                if ($data['configPersonal']['chat_price'] && $data['configPersonal']['chat_price'] > 2) {
                    $data['configPersonal']['chat_price'] = 2;
                }
                if ($data['configPersonal']['voice_price'] && $data['configPersonal']['voice_price'] > 15) {
                    $data['configPersonal']['voice_price'] = 15;
                }
                if ($data['configPersonal']['video_price'] && $data['configPersonal']['video_price'] > 30) {
                    $data['configPersonal']['video_price'] = 30;
                }
            }


            $data['zhaohu'] = 0;
            if ($user_id != $kefu && ($data['zhaohu_time'] + $config['sayhi_times']) < time() && !$id) {
                if (isset($configPersonal['fate_switch']) && ($configPersonal['fate_switch'] + 0)) {
                    $data['zhaohu'] = 1;
                }
            }

            $data['tycoon'] = round($data['tycoon']);
            $data['dy_program'] = explode(',', $data['dy_program']);
            $data['dy_conditions'] = explode(',', $data['dy_conditions']);
            $data['is_vip'] = ($data['noble_grade'] && $data['noble_time'] > time()) ? 1 : 0;
            $data['last_login_datetime'] = changeTime($data);
            $data['self_images'] = $data['self_images'] ? explode(',', $data['self_images']) : [];

            // if ($data['voice_auth'] != 2) {
                $data['voice'] = '';
            // }

            $data['set_paypwd'] = $data['paypwd'] ? 1 : 0;
            $data['register_date'] = date('Y年m月d日', strtotime($data['register_datetime']));
            $data['register_days'] = round((time() - strtotime($data['register_datetime'])) / 3600 / 24);

            /*if ($id && isset($configPersonal['hide_distance']) && ($configPersonal['hide_distance'] + 0)) {
                $data['distance'] = '保密';
                $data['city'] = '';
            } else {
                $distance = $data['xuni_discount'] + 0 ? $data['xuni_discount'] : $data['distance'];
                $data['distance'] = $distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm';
            }

            if ($id && $config['hide_city'] && $data['sex'] == '女') {
                $data['city'] = '';
            }*/
            // $data['city'] = '';

            $data['photo_show'] = UserImg::where(['user_id' => $user_id, 'is_auth' => 0, 'status' => 1])->order('id desc')->limit(10)->cache('photos' . $user_id)->column('pic');
            foreach ($data['photo_show'] as $key => $item) {
                $data['photo_show'][$key] = json_decode($item, true)[0];
            }

            if ($user_id > 30000000) {
                $data['head_portrait'] = _ossUrl(1) . $data['head_portrait'];
            }

            if ($data['photo_show']) {
                if ($data['photo_show'][0] != $data['head_portrait']) {
                    array_unshift($data['photo_show'], $data['head_portrait']);
                }
            } else {
                $data['photo_show'] = [$data['head_portrait']];
            }

            $data['photo_count'] = (new UserImg)->where(['user_id' => $user_id, 'is_auth' => 0, 'status' => 1])->cache('photosCount' . $user_id)->count();

            //$data['state'] = AuthImg::records($user_id, $id);
            $data['state'] = 0;

            /*$imgBurn = ImgBurn::where(['user_id' => $user_id])->column('to_user');
            $data['burn'] = count(array_unique($imgBurn));*/
            $data['burn'] = 0;


            // if (!$configPersonal['hide_charm']) {
            if (false) {
                // 土豪
                //$gradeTycoon = GradeTycoon::where(['min' => ['elt', $data['tycoon']]])->order('grade desc')->find();
                $gradeTycoon = Db::name('grade_tycoon')->where(['min' => ['elt', $data['tycoon']]])->order('grade desc')->cache(true)->find();
                $data['tycoonGrade'] = $gradeTycoon['grade'];
                $data['tycoonName'] = $gradeTycoon['name'];
                $data['tycoonIcon'] = $gradeTycoon['icon'];

                // 魅力
                $gradeCharm = Db::name('grade_charm')->where(['min' => ['elt', $data['charm_value']]])->order('grade desc')->cache(true)->find();
                $data['charmGrade'] = $gradeCharm['grade'];
                $data['charmName'] = $gradeCharm['name'];
                $data['charmIcon'] = $gradeCharm['icon'];
            }

            if (false) {
            //if (!$configPersonal['hide_gift']) {
                $data['gift'] = Db::name('gift_record t1')
                    ->join('gift t2', 't2.id = t1.gift_id')
                    ->where(['t1.to_user' => $user_id])
                    ->order('t1.id desc')
                    ->field('t1.id, t1.gift_id, sum(t1.num) num, t2.name, t2.price, t2.preview, t2.cover,t2.videourl,t2.videojson')
                    ->group('t1.gift_id')
                    ->cache(1800)
                    ->select();
            }

            $data['grade_charm'] = GradeCharm::where(['min' => ['elt', $data['charm_value']]])->order('grade desc')->find();
            if (false) {
            //if (!$configPersonal['hide_defend_angel']) {

                $angel = UserDefend::get(['to_user' => $user_id, 'angel' => 1]);

                // 守护天使
                if (!$data['angel'] || !$angel) {
                    if (!isset($data['charmGrade'])) {
                        $gradeCharm = GradeCharm::where(['min' => ['elt', $data['charm_value']]])->order('grade desc')->find();
                    }

                    if ($data['sex'] == '女') {
                        $angel_min = $gradeCharm['grade'] * $config['female_times'];

                        if ($angel_min < $config['female_min']) {
                            $angel_min = $config['female_min'];
                        }
                    } else {
                        $angel_min = $gradeCharm['grade'] * $config['male_times'];

                        if ($angel_min < $config['male_min']) {
                            $angel_min = $config['male_min'];
                        }
                    }

                    $userDefend = UserDefend::get(['user_id' => $id, 'to_user' => $user_id]);

                    $data['angel_min'] = $userDefend ? $angel_min - $userDefend->money : $angel_min;
                } else {
                    $angel_min = $angel->money;

                    if ($data['sex'] == '女') {
                        if ($angel->money < $config['female_min']) {
                            $angel_min = $config['female_min'];
                        }
                    } else {
                        if ($angel->money < $config['male_min']) {
                            $angel_min = $config['male_min'];
                        }
                    }

                    $userDefend = UserDefend::get(['user_id' => $id, 'to_user' => $user_id]);

                    $data['angel_min'] = $userDefend ? $angel_min - $userDefend->money : $angel_min;

                    $data['angel_avatar'] = UserModel::where(['id' => $angel['user_id']])->value('head_100');

                    $gradeDefend = GradeDefend::where(['min' => ['elt', $angel['money']]])->order('grade desc')->find();

                    $data['angel_name'] = $gradeDefend['name'];
                    $data['angel_grade'] = $gradeDefend['grade'];
                    $data['angel_icon'] = $gradeDefend['icon'];
                }

                $data['angel_min'] = $data['angel_min'] ?: 1;
            }

            if (false) {
            //if (!$configPersonal['hide_defends']) {
                $data['defends_count'] = Db::name('user_defend')->where(['to_user' => $user_id])->count();
                $data['defends'] = Db::name('user_defend t1')
                    ->field('t1.id, t1.user_id userid, t1.angel, t1.money, t1.update_time, t2.name,t2.head_100')
                    ->join('user t2', 't2.id = t1.user_id')
                    ->where(['t1.to_user' => $user_id])
                    ->order('t1.money desc')->limit(3)->select();

                foreach ($data['defends'] as $key => $item) {
                    $data['defends'][$key]['intimate'] = sprintf("%.1f", $item['money'] * 0.1);
                    $data['defends'][$key]['days'] = ceil((time() - $item['update_time']) / 86400);

                    unset($data['defends'][$key]['money'], $data['defends'][$key]['money']);
                }
            }

            // 周星勋章
            /*$liveUserStar = Db::name('live_user_star')->where(['user_id' => $user_id, 'level' => 1])->select();

            if ($liveUserStar) {
                $gift_ids = array_column($liveUserStar, 'gift_id');
                $preview = Db::name('gift')->where(['id' => ['in', $gift_ids]])->column('id, preview');
                $liveMedal = Db::name('live_medal')->column('types, icon');

                foreach ($liveUserStar as $m => $n) {
                    if ($n['gift_id']) {
                        if (isset($preview[$n['gift_id']])) {
                            $data['week_star'][] = ['cover' => changeUrl($preview[$n['gift_id']]), 'icon' => changeUrl($liveMedal[1])];
                        }
                    } else {
                        $data['super_star'][] = ['icon' => changeUrl($liveMedal[2])];
                    }
                }
            }*/
            $other = false;
            if ($id && $user_id != $id) {
                $other = true;


                // $limittime = strtotime('2023-04-15 00:00:00');
                // if (time() >= $limittime) {
                //     $myinfo = Db::name('user')->find($id);
                //     if ((strtotime($data['register_datetime']) < $limittime && strtotime($myinfo['register_datetime']) > $limittime) || (strtotime($data['register_datetime']) > $limittime && strtotime($myinfo['register_datetime']) < $limittime)) {
                //         return $this->miss('获取用户资料失败');
                //     }
                // }

                /*$user = (new UserModel)->field('sex, yqm')->where(['id' => $id])->cache(86400)->find();

                if ($user['sex'] == '女' && $user['yqm'] && $user['yqm'] == $data['yqr']) {
                    $data['volley'] = $data['volley'] * 0.9;
                    $data['volley'] = floor($data['volley'] * 100) / 100;
                } else {
                    $data['volley'] = 0;
                }*/
                $data['volley'] = changefloor($data['volley'] * 0.9);

                $blacklist = Blacklist::where(['user_id' => $user_id, 'to_user' => $id])->cache('black' . $user_id . '_' . $id)->find();
                $data['pull_black'] = $blacklist ? 1 : 0;

                $attention = Attention::where(['user_id' => $id, 'to_user' => $user_id])->cache('follow' . $id . '_' . $user_id)->find();
                $data['love'] = $attention ? 1 : 0;


                // 聊天打折
                $overpayscale = 0;
                // 获取所有关联账号的总支付
                $overpayscale = UserIntimateService::Count($id, $user_id, true);
                if ($overpayscale) {
                    $chat_scale['scale'] = $overpayscale;
                } else {
                    $chat_scale = Db::name('limit_chat_price')->where($id>$user_id ? 'user_id='.$user_id. ' and another_id='. $id : 'user_id='.$id. ' and another_id='. $user_id)->find();
                }

                if ($chat_scale) {
                    $data['configPersonal']['chat_price'] = isset($data['configPersonal']['chat_price']) ? round($data['configPersonal']['chat_price'] * $chat_scale['scale'] / 100, 2) : 0;
                    $data['configPersonal']['voice_price'] = isset($data['configPersonal']['voice_price']) ? round($data['configPersonal']['voice_price'] * $chat_scale['scale'] / 100, 2) : 0;
                    $data['configPersonal']['video_price'] = isset($data['configPersonal']['video_price']) ? round($data['configPersonal']['video_price'] * $chat_scale['scale'] / 100, 2) : 0;
                }

                /*if ($data['notlimit_city']) {
                    $data['city'] = $user['city'];
                }*/

                /*if (($user->sex == '女' && !$user->attestation) ||
                    ($user->sex == '男' && (!$user->noble_grade || $user->noble_time < time()))) {

                    $templete = [
                        'user_id' => $user_id,
                        'to_user' => $id,
                        'type' => 5,
                        'date' => date('Y-m-d'),
                    ];

                    $vipNum = VipNum::get($templete);

                    if ($vipNum) {
                        VipNum::create($templete);
                    }
                }*/
                
                $seeRecord = SeeRecord::get(['user_id' => $user_id, 'the_user' => $id]);
                if ($seeRecord) {
                    SeeRecord::update(['id' => $seeRecord->id, 'addtime' => date("Y-m-d H:i:s")]);
                } else {
                    SeeRecord::create(['user_id' => $user_id, 'the_user' => $id]);
                }
    
                /*$result = VipNum::where(['user_id' => $id, 'to_user' => $user_id, 'type' => 1])->column('types');
                $chaoe = Chaoe::where(['user_id' => $id, 'to_user' => $user_id, 'type' => 2])->column('types');
    
                $data['wechat_link'] = $data['qq_link'] = $data['phone_link'] = 0;
                if (intval($config['old_users_switch'])) {
                    if (in_array(1, $result) || in_array(1, $chaoe)) {
                        $data['wechat_link'] = 1;
                    }
                    if (in_array(2, $result) || in_array(2, $chaoe)) {
                        $data['qq_link'] = 1;
                    }
                    if (in_array(3, $result) || in_array(3, $chaoe)) {
                        $data['phone_link'] = 1;
                    }
                } else {
                    $data['wxcount'] = $data['qq'] = 0;
                }*/
                $data['wxcount'] = $data['qq'] = 0;
                

                /*if ($result) {
                    $pingjia = Pingjia::get(['user_id' => $id, 'to_user' => $user_id]);
                    $data['pingjia'] = $pingjia ? 2 : 0;
                } else {
                    $data['pingjia'] = 1;
                }*/
                $data['pingjia'] = 0;

                $couple = $id < $user_id ? $id . ',' . $user_id : $user_id . ',' . $id;
                $userIntimate = UserIntimate::get(['couple_a' => $couple]);
                $data['intimate'] = $userIntimate ? $userIntimate['intimate'] : 0;

                $configPersonal = ConfigPersonal::get(['user_id' => $id]);

                if (!$configPersonal || !$configPersonal['hide_visit']) {
                    UserModel::where(['id' => (int)$user_id])->setInc('see');
                }
                $mine = Db::name('user')->find($id);
                // if(($mine['yqr'] && $mine['sex'] == '男') || strtotime($mine['register_datetime']) < $this->regnewtime){
                    // $data['city'] = '';
                    // $data['offten_city'] = '';
                    // $data['through_membership'] = '';
                    // $data['age'] = 0;
                // }



                $ChatChargeRecordsMap = [
                    'user_id' => $user_id,
                    'another_id' => $id,
                ];
                $ChatChargeRecordsField = 'user_remark';
                if ($id < $user_id) {
                    $ChatChargeRecordsMap = [
                        'user_id' => $id,
                        'another_id' => $user_id,
                    ];
                    $ChatChargeRecordsField = 'another_remark';
                }

                $remarkname = Db::name('chat_charge_records')->where($ChatChargeRecordsMap)->value($ChatChargeRecordsField);
                $data['remarkname'] = $remarkname ?? '';

                $data['in_blacklist'] = Db::name('blacklist')->where(['user_id'=>$id, 'to_user'=>$user_id])->count();
                $data['hide_chat'] = $user_id > 30000000;

                $data['institutional'] = Db::name('user_attestation')->where(['user_id'=>$user_id, 'status'=>1, 'types'=>4])->value('hospital');

                $experience = Db::name('user_attestation')->where(['types'=>['<=',5],'user_id'=>$user_id, 'status'=>1])->column('category');
                $experience = implode(',',$experience);
                $data['experience'] = Db::name('topic')->where(['id'=>['in',$experience]])->column('name');


                // if(strtotime($mine['register_datetime']) < $this->regnewtime || $mine['sex'] == '女'){
                //     unset($data['configPersonal']['chat_price'], $data['configPersonal']['voice_price'], $data['configPersonal']['video_price']);
                // }
                unset($data['zhifucount'], $data['zhifuname'], $data['wechat'], $data['wechat_name'], $data['phone']);
            } else {
                $task_contain = ['avatar', 'voice', 'info', 'more_info', 'perfect_info', 'real_avatar'];
                $taskWhere = ['name' => ['in', $task_contain]];
                $taskWhere['sex_limit'] = $data['sex'] == '女' ? ['in', [0, 1]] : ['in', [0, 2]];
                $tasks = Db::name('task')->where($taskWhere)->cache('task')->column('name, title, reward, reward_type');
                $userTask = Db::name('user_task')->where(['task' => ['in', $task_contain], 'user_id' => $user_id])->cache('userTask' . $user_id)->column('task');

                $task = [];
                foreach ($task_contain as $item) {
                    if (isset($tasks[$item]) && ($tasks[$item]['reward'] + 0) && !in_array($item, $userTask)) {
                        $task[$item] = ['title' => $tasks[$item]['title'], 'reward' => $tasks[$item]['reward'], 'reward_type' => $tasks[$item]['reward_type']];
                    }
                }

                $data['task'] = $task;

                
                $data['frozen_score'] = Db::name('wallet_frozen')->where(['user_id'=>$user_id])->value('value');
                $data['frozen_score'] = $data['frozen_score'] ?? 0;
                
                $data['limit_age_change'] = Db::name('change_age_limit')->where(['user_id'=>$user_id])->find();
                $data['limit_age_change'] = $data['limit_age_change'] ? 1 : 0;

                $data['charging_settings'] = 1;
                // if (isset($config['two_way_charge_status']) && $config['two_way_charge_status'] && $data['sex'] == '男') {
                //     $data['charging_settings'] = strtotime($data['register_datetime']) > strtotime($config['two_way_charge_reg_time']);
                // }
                $data['changeHeadInfo'] = Db::name('user_material_verify')->where(['types'=>1,'user_id'=>$user_id,'status'=>0])->field('content,status')->order('id desc')->find();

                $data['is_banned'] = 0;
            }


            $data['dy_count'] = Db::name('dymanic')
                            ->where(['shenhe'=>$other?1:['>=',-1], 'userid'=>$user_id, 'state'=>0])
                            ->count();
            $data['dy_count'] = $data['dy_count'] ? $data['dy_count'] : '0';
            $data['ser_count'] = Db::name('user_service')
                            ->where(['user_id'=>$user_id,'state'=>$other?1:['>=',-1]])
                            ->count();
            $data['mix_count'] = Db::name('dymanic_collection')
                            ->where(['user_id'=>$user_id,'state'=>$other?1:['>=',-1],'count'=>['>=',$other?1:0]])
                            ->count();

                // $data['stature'] = '';
                // $data['weight'] = '';
                // $data['city'] = '';
                // $data['occupation'] = '';
                $data['school_of_graduation'] = '';
                // $data['through_membership'] = '';
                // $data['live_status'] = '';
            $data['volley'] = intval($data['volley']);

            if (intval($config['family_switch'])) {
                $cluster = Cluster::get(['types' => 1, 'user_id' => $user_id, 'status' => 1]);

                if ($cluster) {
                    $data['cluster'] = [
                        'id' => $cluster['id'],
                        'name' => $cluster['name'],
                        'logo' => changeUrl($cluster['logo']),
                        'count' => $cluster['count'],
                        'ranking' => $cluster['ranking'],
                    ];
                } else {
                    $data['cluster'] = [];
                }
            } else {
                $data['cluster'] = [];
            }


            if ($data['noble_time'] > time() && $data['noble_grade']) {
                $data['is_noble'] = 1;

                $gradeNoble = GradeNoble::where(['grade' => $data['noble_grade']])->cache(86400)->find();

                if ($gradeNoble) {
                    $data['noble'] = [
                        'id' => $gradeNoble['id'],
                        'name' => $gradeNoble['name'],
                        'grade' => $gradeNoble['grade'],
                        'icon' => $gradeNoble['icon'],
                        'circle' => $gradeNoble['circle'],
                    ];
                } else {
                    $data['noble'] = [];
                }

                $data['noble_time'] = date('Y-m-d H:i:s', $data['noble_time']);
            } else {
                $data['is_noble'] = 0;
            }

            $userZan = UserZan::where(['types' => 2, 'user_id' => $id, 'to_user' => $user_id])->cache('zan' . $id . '_' . $user_id)->find();

            $data['had_voice_zan'] = $userZan ? 1 : 0;

            /*if ($data['tags']) {
                $tags = explode(',', $data['tags']);

                $data['tags'] = Db::name('tags')->where(['id' => ['in', $tags]])->column('name');
            } else {
                $data['tags'] = [];
            }*/
            $data['tags'] = [];
            unset($data['xuni_discount'], $data['notlimit_city'], $data['user_distance'], $data['paypwd']);

            $data['count_zan'] = 0;
            $data['count_exp'] = 0;
            $data['count_col'] = 0;
            $dys = Db::name('dymanic')->where(['userid'=>$user_id])->field('thumbsup,xuni_thumbsup,lover')->select();
            $dys2 = Db::connect('database9')->name('dymanic')->where(['userid'=>$user_id])->field('thumbsup,xuni_thumbsup,lover')->select();
            $data['count_zan'] = array_sum(array_column($dys, 'thumbsup')) + array_sum(array_column($dys, 'xuni_thumbsup')) + array_sum(array_column($dys2, 'thumbsup')) + array_sum(array_column($dys2, 'xuni_thumbsup'));
            $data['count_exp'] = array_sum(array_column($dys, 'lover')) + array_sum(array_column($dys2, 'lover'));
            $data['count_col'] = sizeof($dys2);
        }

        return $this->pass($data, 'result');
    }

    public function userVolley()
    {
        $user_id = $this->params['user_id'] ?? 0;
        if (!$user_id) {
            return $this->miss('');
        }
        $key = $this->member['sex'] == '女' ? 'beans' : 'volley';
        $volley = UserModel::where('id', $user_id)->value($key);
        $volley = intval($volley);
        return $this->pass($volley, 'volley');
    }

    public function volleyDesc(Request $request = null)
    {
        $page = $request->param('page') ? $request->param('page') + 1 : 1;
        $pagesize = $request->param('pagesize') ?: 10;

        $data = Db::name('topup')
            ->field('id, price, money, state, numbers number, addtime time')
            ->where(['fk_userid' => $this->params['user_id']])
            ->order('id desc')->page($page, $pagesize)->select();

        foreach ($data as $key => $item) {
            if (!$item['state']) {
                $data[$key]['state'] = "充值中断";
                $data[$key]['msg'] = "请检查您的余额是否充足";
            } else if ($item['state'] == 1) {
                $data[$key]['state'] = "充值成功";
                $data[$key]['msg'] = "感谢您对我们的支持";
            }

            $data[$key]['time'] = date('m-d H:i:s', strtotime($item['time']));
        }

        return $this->pass($data, 'result');
    }

    public function userPay(Request $request = null)
    {
        $page = $request->param('page') ? $request->param('page') + 1 : 1;
        $pagesize = $request->param('pagesize') ?: 10;

        $data = Db::name('volley_desc')
            ->field('id, price, state, desc, content, time')
            ->where(['user_id' => $this->params['user_id']])
            ->order('id desc')->page($page, $pagesize)->select();

        foreach ($data as $key => $item) {
            if (!$item['desc']) {
                $data[$key]['type'] = "余额支付";
            } else if ($item['desc'] == 1) {
                $data[$key]['type'] = "微信支付";
            } else if ($item['desc'] == 2) {
                $data[$key]['type'] = "支付宝支付";
            }

            $data[$key]['state'] = $item['state'] ? "充值服务" : "购买服务";

            $data[$key]['time'] = date('m-d H:i:s', $item['time']);

            unset($data[$key]['desc']);
        }

        return $this->pass($data, 'result');
    }

    public function editHead()
    {
        $config = Config::where(['title' => ['in', ['check_avatar']]])->column('title, content');
        $face = input('face', 0);

        $user = UserModel::get($this->params['user_id']);
        if (!$user) return $this->return['user.error.notExist'];
        // if ($user['sex'] == '女') {
        //     if ($user['is_identity_authentication'] != 2) {
        //         return $this->miss('未真人认证，头像不可更改');
        //     }
        //     $face = 1;
        // }
        if (!$face) {
            $limit_change_age = Db::name('change_age_limit')->where(['user_id'=>$this->params['user_id']])->find();
            $face = $limit_change_age ? 1 : $face;
        }

        $is_face = 0;
        if ($face){
            $FaceAuth = new FaceAuth;
            $authpic = Db::name('auth')->where(['user_id'=>$this->params['user_id']])->value('image1');
            if(!$authpic){
                return json_encode(['code' => 400, 'msg' => '未真人认证，无法上传人脸匹配图片到头像']);
            }
            $path = getenv('APP_OSS') ? 'http://' . getenv('OSS_BUCKET') . '.' . getenv('OSS_ENDPOINT') : SITE_PATH;
            $authpic = (strstr(PHP_OS, 'WIN') ? 'http://' . getenv('APP_URL') : $path) . $authpic;

            try {
                $FAres = $FaceAuth->comparebaidu($path . $this->params['head'], $authpic);
            } catch (\Exception $e) {
                $FAres = true;
            }
            if($FAres){
                return json_encode(['code' => 400, 'msg' => '本次更换头像与真人认证上传图人脸不符，请重新上传']);
            } else {
                $is_face = 1;
            }
        }

        // if ($this->member['sex'] == '女') {
            // $config['check_avatar'] = 0;
        // }

        if ($config['check_avatar']) {
            UserMaterialVerify::index(1, $this->params['user_id'], $this->params['head'], $is_face);
            // 任务
            Task::finish('avatar', $this->member['id']);

            return $this->return['common.success.check'];
        } else {
            // if ($this->member['sex'] == '女') {
                UserMaterialVerify::index(1, $this->params['user_id'], $this->params['head'], $is_face, 1);
            // }

            $thumb_ = explode('.', $this->params['head']);
            $thumb = $thumb_[0] . '_thumb.' . $thumb_[1];

            $data = [
                'id' => $this->params['user_id'],
                'head_100' => $thumb,
                'head_300' => $thumb,
                'head_portrait' => $this->params['head'],
                'real_avatar' => $is_face,
            ];

            UserModel::update($data);

            UserImg::where(['types' => 1, 'user_id' => $this->params['user_id']])->setField('is_avatar', 0);
            UserImg::create([
                'user_id' => $this->params['user_id'],
                'pic' => json_encode([$this->params['head']], JSON_UNESCAPED_SLASHES),
                'picthumb' => json_encode([$thumb], JSON_UNESCAPED_SLASHES),
                'is_avatar' => 1,
                'is_face'   => $is_face
            ]);
        
            Cache::rm('photos' . $this->params['user_id']);
            Cache::rm('photosCount' . $this->params['user_id']);

            // 任务
            Task::finish('avatar', $this->member['id']);

            if ($is_face) {
                Task::finish('real_avatar', $this->member['id']);
            }

            (new \app\service\TencentIM)->account_import($this->member['id'], $this->member['name'], $this->params['head']);
            return $this->return['common.success.update'];
        }
    }

    public function editPwd(Request $request = null)
    {
        $email = false;
        $phone = false;
        if ($request->param('user_id')) {
            $user_id = intval($request->param('user_id'));
            $user = UserModel::get($user_id);

            if (!$user) return $this->return['user.error.notExist'];
            $email = Db::name('user_auth')->where(['user_id'=>$user_id, 'type'=>1, 'state'=>1])->value('account');
            if ($user['reg'] == 0) {
                if ($request->param('phone')) {
                    $phone = $request->param('phone');
                } else {
                    return $this->return['common.error.paramMiss'];
                }
            } else if ($user['phone']) {
                $phone = $user['phone'];
            } else if ($email) {
            } else {
                return $this->miss('请先绑定手机或邮箱');
            }
        } else if ($request->param('phone')) {
            $phone = $request->param('phone');
        } else if ($request->param('email')) {
            $email = $request->param('email');
        } else {
            return $this->return['common.error.paramMiss'];
        }

        if(!isset($this->params['code'])){
            return $this->miss('请输入验证码');
        }
        if ($phone) {
            $user = UserModel::where(['phone' => $phone])->find();
            if (!$user) return $this->miss('未注册');
            $result = _isMobile($phone, '86');
            if ($result['code'] == 400) {
                return $this->miss($result['msg']);
            }
            $result = Code::verifyCode($phone, $this->params['code']);
        } else if ($email) {
            $user_id = Db::name('user_auth')->where(['account'=>$email, 'type'=>1, 'state'=>1])->value('user_id');
            $user = UserModel::get($user_id);
            if (!$user) return $this->miss('未注册');
            if (!_isEmail($email)) {
                return $this->miss('邮箱异常');
            }
            $result = Code::verifyEmailCode($email, $this->params['code']);
        }

        if ($result['code'] == 400) {
            return $this->miss($result['msg']);
        }

        //UserModel::where(['id' => $user['id']])->update(['password' => $this->params['password']]);
        //为保证安全 密码使用加密方式进行存储
        $inputPassword=$this->params['password'];
        $hashedPassword = UserModel::encryptPassword($inputPassword);
        UserModel::where(['id' => $user['id']])->update(['password' => $hashedPassword]);
        UserWarn::CheckWarn($user['id'], '修改登录密码');

        return $this->return['common.success.update'];
    }

    // public function editInfoold()
    // {
    //     if (isset($this->params['bank_number'])) {
    //         $origin_result = $this->editBankcard();
    //         $result = $origin_result->getData();
    //         if ($result['code']!=200) return $origin_result;
    //     }
    //     $this->params['user_id'] = $this->params['user_id'] ?? $this->member['id'];
    //     $this->params['city'] = $this->params['offten_city'];
    //     $success_text = '修改成功';
    //     $config = Config::index('check');
    //     $contain = ['id', 'volley', 'score', 'password', 'sex', 'head_100', 'head_300', 'head_portrait'];
    //     // 基本资料
    //     $info = ['name', 'sex', 'birthday', 'city', 'stature', 'emotion', 'education_background', 'monthly_salary', 'occupation', 'slogan'];
    //     // 更多资料
    //     $more_info = ['school_of_graduation', 'weight', 'through_membership', 'live_status', 'is_house_purchase', 'is_car_purchase'];
    //     // 自我介绍
    //     $perfect_info = ['self_slogan'];

    //     $auths = [
    //         'education_background' => 'is_education_authentication',
    //         'is_car_purchase' => 'car_auth',
    //         'is_house_purchase' => 'house_auth',
    //         'monthly_salary' => 'income_auth',
    //         'emotion' => 'marry_auth',
    //     ];

    //     $xuniEdit = [];

    //     $minganci = Db::name('filter_word')->where(['state' => 1])->column('name');

    //     $infoFields = Db::getTableInfo('user', 'fields');


    //     $clearConfigPrice = false;
    //     foreach ($this->params as $key => $value) {
    //         if (in_array($key, $contain)) {
    //             unset($this->params[$key]);
    //         }
    //         if (!in_array($key, $infoFields) && !in_array($key, ['user_id', 'code'])) {
    //             unset($this->params[$key]);
    //         }

    //         if (in_array($key, $info)) {
    //             unset($info[array_search($key, $info)]);
    //         }

    //         if (in_array($key, array_keys($auths))) {
    //             $state = $this->member[$auths[$key]];
    //             if (in_array($state, [1,2])) {
    //                 unset($this->params[$key]);
    //             }
    //         }

    //         if (in_array($key, $more_info) && $value) {
    //             unset($more_info[array_search($key, $more_info)]);
    //         }

    //         if (in_array($key, $perfect_info) && $value) {
    //             unset($perfect_info[array_search($key, $perfect_info)]);
    //         }
    //         if ($key == 'birthday') {
    //             unset($this->params['self_slogan']);
    //             $changeagelimit = false;
    //             if ($this->member['age']) {
    //                 $changeagelimit = Db::name('change_age_limit')->where(['user_id'=>$this->member['id']])->find();
    //             }
    //             if($changeagelimit){
    //                 unset($this->params['birthday']);
    //             }else{
    //                 if ($value) {
    //                     $xuniEdit['age'] = $this->params['age'] = countage($value);

    //                     $idcardnumber = Db::name('user_certification')->where(['user_id'=>$this->member['id'], 'status'=>1])->value('data');
    //                     if ($idcardnumber) {
    //                         $age = countage(_getDateFromIdcard($idcardnumber));
    //                         if ($age) {
    //                             // if ($this->params['age'] > $age + 5 || $age - 5 > $this->params['age']) {
    //                             //     unset($this->params['age']);
    //                             //     unset($this->params['birthday']);
    //                             //     $success_text = '请填写真实的年龄，不得大于或者小于身份证年龄的5岁';
    //                             // }
    //                         }
    //                     }
    //                     if (isset($this->params['age']) && $this->member['age'] != $this->params['age']) {
    //                         $clearConfigPrice = true;
    //                     }
    //                 } else {
    //                     $this->params['birthday'] = '';
    //                 }
    //             }
    //         }

    //         if ($key == 'voice' && $value && $value != $this->member['voice']) {
    //             $result = Db::name('user_certification')->where(['types' => 5, 'user_id' => $this->member['id']])->find();
    //             if ($result) {
    //                 Db::name('user_certification')->where(['id' => $result['id']])->update(['image_front' => $value, 'status' => 0, 'reason' => '', 'update_time' => time()]);
    //             } else {
    //                 Db::name('user_certification')->insert([
    //                     'types' => 5,
    //                     'user_id' => $this->member['id'],
    //                     'image_front' => $value,
    //                     'create_time' => time(),
    //                     'update_time' => time()
    //                 ]);
    //             }

    //             $this->params['voice_auth'] = 1;
    //         }

    //         if(in_array($key, ['name', 'self_slogan', 'slogan'])){
    //             $keynames = ['name'=>'昵称','self_slogan'=>'自我介绍','slogan'=>'个性签名'];


    //             if(ishasPhoneNumber($value)){
    //                 exit(json_encode(['code' => 400, 'msg' => $keynames[$key] . '禁止输入手机号']));
    //             }


    //             foreach ($minganci as $v) {
    //                 if (stripos($value, $v) !== false) {
    //                     exit(json_encode(['code' => 400, 'msg' => $keynames[$key] . '含有敏感词"' . $v . '",请重新编辑']));
    //                 }
    //             }
    //             if ($key == 'name' && empty($value)) {
    //                 unset($this->params['name']);
    //             }
    //         }

    //         if (in_array($key, ['phone', 'paypwd'])) {
    //             if (!isset($this->params['code']) || !$this->params['code']) {
    //                 return $this->return['sms.error.code'];
    //             }

    //             // if (!isset($this->params['device_id']) || !$this->params['device_id']) {
    //             //     return $this->miss('设备错误');
    //             // }

    //             // if ($this->member['device_id'] != $this->params['device_id']) {
    //             //     return $this->miss('设备错误');
    //             // }

    //             $phone = $key == 'phone' ? $value : $this->member['phone'];

    //             $result = Code::verifyCode($phone, $this->params['code']);
    //             if ($result['code'] == 400) {
    //                 return $this->miss($result['msg']);
    //             }

    //             if ($key == 'paypwd') {
    //                 $this->params[$key] = password_hash($value, PASSWORD_DEFAULT);
    //             }

    //             unset($this->params['code']);
    //         }

    //         if ($key == 'occupation') {
    //             if ($value) {
    //                 $hasoccupation = Db::name('user_occupation')->where(['name'=>$value])->find();
    //                 if (!$hasoccupation) unset($this->params['occupation']);
    //             }
    //         }
    //     }

    //     $this->params['id'] = $this->params['user_id'];
    //     unset($this->params['user_id']);

    //     if (!isset($this->params['city'])) {
    //         try {
    //             $ip = (new Whip())->getValidIpAddress();
    //             $ipinfo = IpInfoUtils::info($ip);
    //             if ($ip && $ipinfo) {
    //                 if (isset($ipinfo['city']) && $ipinfo['city']) {
    //                     if(strpos($ipinfo['city'],'市') !== false) {
    //                         $ipinfo['city'] = substr($ipinfo['city'],0,strrpos($ipinfo['city'],'市'));
    //                     }
    //                     $this->params['offten_city'] = $this->params['city'] = $ipinfo['city'];
    //                 }
    //                 if (isset($ipinfo['province']) && $ipinfo['province']) {
    //                     if(strpos($ipinfo['province'],'省') !== false) {
    //                         $ipinfo['province'] = substr($ipinfo['province'],0,strrpos($ipinfo['province'],'省'));
    //                     }
    //                     $this->params['province'] = $ipinfo['province'];
    //                 }
    //                 if (!$this->params['offten_city']) {
    //                     unset($this->params['offten_city'], $this->params['city']);
    //                 }
    //                 if (!$this->params['province']) {
    //                     unset($this->params['province']);
    //                 }
    //             }
    //         } catch (\Exception $e) {
                
    //         }
    //     }

    //     if (isset($this->params['name']) && $this->params['name'] != $this->member['name']) {
    //         $nickExist = Db::name('user')->where(['name'=>$this->params['name'], 'reg'=>1])->count();
    //         if ($nickExist) {
    //             return $this->miss('昵称已被占用');
    //         }
    //     }

    //     if (isset($this->params['name']) && $this->params['name'] != $this->member['name'] && isset($config['check_edit_nickname']) && $config['check_edit_nickname'] == 1) {

    //         $limit = UserDeedLimit::check($this->member['id'], 3);
    //         if ($limit) {
    //             return $this->miss('当前已被限制修改昵称');
    //         }
    //         UserMaterialVerify::index(3, $this->member['id'], $this->params['name']);
    //         (new \app\service\TencentIM)->account_import($this->member['id'], $this->params['name'], $this->member['head_portrait']?:$this->member['head_100']);
    //         // unset($this->params['name']);
    //     }
    //     if (isset($this->params['slogan']) && $this->params['slogan'] && isset($config['check_edit_slogan']) && $config['check_edit_slogan'] == 1) {
    //         UserMaterialVerify::index(4, $this->member['id'], $this->params['slogan']);
    //         // unset($this->params['slogan']);
    //     }
    //     if (isset($this->params['self_slogan']) && $this->params['self_slogan'] && isset($config['check_edit_self_slogan']) && $config['check_edit_self_slogan'] == 1) {
    //         UserMaterialVerify::index(6, $this->member['id'], $this->params['self_slogan']);
    //         // unset($this->params['self_slogan']);
    //     }
    //     if (isset($this->params['cover']) && $this->params['cover'] && $this->params['cover'] != $this->member['cover']) {
    //         UserMaterialVerify::index(7, $this->member['id'], $this->params['cover']);
    //     }
    //     UserModel::update($this->params);
    //     if (sizeof($xuniEdit)) {
    //         Db::name('user')->where(['reg'=>2,'authcode'=>$this->member['id']])->update($xuniEdit);
    //     }
    //     // if ($clearConfigPrice) {
    //     //     Db::name('config_personal')->where(['user_id'=>$this->member['id']])->update(['chat_price'=>0,'voice_price'=>0,'video_price'=>0]);
    //     // }

    //     if (!$info) {
    //         // 任务
    //         Task::finish('info', $this->member['id']);
    //     }

    //     if (!$more_info) {
    //         // 任务
    //         Task::finish('more_info', $this->member['id']);
    //     }

    //     if (!$perfect_info) {
    //         // 任务
    //         Task::finish('perfect_info', $this->member['id']);
    //     }
    //     // UserProfile::change($this->member['id'], $this->params);
    //     return $this->pass($success_text);
    // }
    
    //     public function editInfo()
    // {
    //     if (isset($this->params['bank_number'])) {
    //         $origin_result = $this->editBankcard();
    //         $result = $origin_result->getData();
    //         if ($result['code']!=200) return $origin_result;
    //     }
    //     $this->params['user_id'] = $this->params['user_id'] ?? $this->member['id'];
    //     $this->params['city'] = $this->params['offten_city'];//修正app地址修改不成功的问题
    //     $success_text = '修改成功';
    //     $config = Config::index('check');
    //     $contain = ['id', 'volley', 'score', 'password', 'sex', 'head_100', 'head_300', 'head_portrait'];
    //     // 基本资料
    //     $info = ['name', 'sex', 'birthday', 'city', 'stature', 'emotion', 'education_background', 'monthly_salary', 'occupation', 'slogan'];
    //     // 更多资料
    //     $more_info = ['school_of_graduation', 'weight', 'through_membership', 'live_status', 'is_house_purchase', 'is_car_purchase'];
    //     // 自我介绍
    //     $perfect_info = ['self_slogan'];

    //     $auths = [
    //         'education_background' => 'is_education_authentication',
    //         'is_car_purchase' => 'car_auth',
    //         'is_house_purchase' => 'house_auth',
    //         'monthly_salary' => 'income_auth',
    //         'emotion' => 'marry_auth',
    //     ];

    //     $xuniEdit = [];

    //     $minganci = Db::name('filter_word')->where(['state' => 1])->column('name');

    //     $infoFields = Db::getTableInfo('user', 'fields');


    //     $clearConfigPrice = false;
    //     foreach ($this->params as $key => $value) {
    //         if (in_array($key, $contain)) {
    //             unset($this->params[$key]);
    //         }
    //         if (!in_array($key, $infoFields) && !in_array($key, ['user_id', 'code'])) {
    //             unset($this->params[$key]);
    //         }

    //         if (in_array($key, $info)) {
    //             unset($info[array_search($key, $info)]);
    //         }

    //         if (in_array($key, array_keys($auths))) {
    //             $state = $this->member[$auths[$key]];
    //             if (in_array($state, [1,2])) {
    //                 unset($this->params[$key]);
    //             }
    //         }

    //         if (in_array($key, $more_info) && $value) {
    //             unset($more_info[array_search($key, $more_info)]);
    //         }

    //         if (in_array($key, $perfect_info) && $value) {
    //             unset($perfect_info[array_search($key, $perfect_info)]);
    //         }
    //         if ($key == 'birthday') {
    //             unset($this->params['self_slogan']);
    //             $changeagelimit = false;
    //             if ($this->member['age']) {
    //                 $changeagelimit = Db::name('change_age_limit')->where(['user_id'=>$this->member['id']])->find();
    //             }
    //             if($changeagelimit){
    //                 unset($this->params['birthday']);
    //             }else{
    //                 if ($value) {
    //                     $xuniEdit['age'] = $this->params['age'] = countage($value);

    //                     $idcardnumber = Db::name('user_certification')->where(['user_id'=>$this->member['id'], 'status'=>1])->value('data');
    //                     if ($idcardnumber) {
    //                         $age = countage(_getDateFromIdcard($idcardnumber));
    //                         if ($age) {
    //                             // if ($this->params['age'] > $age + 5 || $age - 5 > $this->params['age']) {
    //                             //     unset($this->params['age']);
    //                             //     unset($this->params['birthday']);
    //                             //     $success_text = '请填写真实的年龄，不得大于或者小于身份证年龄的5岁';
    //                             // }
    //                         }
    //                     }
    //                     if (isset($this->params['age']) && $this->member['age'] != $this->params['age']) {
    //                         $clearConfigPrice = true;
    //                     }
    //                 } else {
    //                     $this->params['birthday'] = '';
    //                 }
    //             }
    //         }

    //         if ($key == 'voice' && $value && $value != $this->member['voice']) {
    //             $result = Db::name('user_certification')->where(['types' => 5, 'user_id' => $this->member['id']])->find();
    //             if ($result) {
    //                 Db::name('user_certification')->where(['id' => $result['id']])->update(['image_front' => $value, 'status' => 0, 'reason' => '', 'update_time' => time()]);
    //             } else {
    //                 Db::name('user_certification')->insert([
    //                     'types' => 5,
    //                     'user_id' => $this->member['id'],
    //                     'image_front' => $value,
    //                     'create_time' => time(),
    //                     'update_time' => time()
    //                 ]);
    //             }

    //             $this->params['voice_auth'] = 1;
    //         }

    //         if(in_array($key, ['name', 'self_slogan', 'slogan'])){
    //             $keynames = ['name'=>'昵称','self_slogan'=>'自我介绍','slogan'=>'个性签名'];


    //             if(ishasPhoneNumber($value)){
    //                 exit(json_encode(['code' => 400, 'msg' => $keynames[$key] . '禁止输入手机号']));
    //             }


    //             foreach ($minganci as $v) {
    //                 if (stripos($value, $v) !== false) {
    //                     exit(json_encode(['code' => 400, 'msg' => $keynames[$key] . '含有敏感词"' . $v . '",请重新编辑']));
    //                 }
    //             }
    //             if ($key == 'name' && empty($value)) {
    //                 unset($this->params['name']);
    //             }
    //         }

    //         if (in_array($key, ['phone', 'paypwd'])) {
    //             if (!isset($this->params['code']) || !$this->params['code']) {
    //                 return $this->return['sms.error.code'];
    //             }

    //             // if (!isset($this->params['device_id']) || !$this->params['device_id']) {
    //             //     return $this->miss('设备错误');
    //             // }

    //             // if ($this->member['device_id'] != $this->params['device_id']) {
    //             //     return $this->miss('设备错误');
    //             // }

    //             $phone = $key == 'phone' ? $value : $this->member['phone'];

    //             $result = Code::verifyCode($phone, $this->params['code']);
    //             if ($result['code'] == 400) {
    //                 return $this->miss($result['msg']);
    //             }

    //             if ($key == 'paypwd') {
    //                 $this->params[$key] = password_hash($value, PASSWORD_DEFAULT);
    //             }

    //             unset($this->params['code']);
    //         }

    //         if ($key == 'occupation') {
    //             if ($value) {
    //                 $hasoccupation = Db::name('user_occupation')->where(['name'=>$value])->find();
    //                 if (!$hasoccupation) unset($this->params['occupation']);
    //             }
    //         }
    //     }

    //     $this->params['id'] = $this->params['user_id'];
    //     unset($this->params['user_id']);

    //     if (!isset($this->params['city'])) {
    //         try {
    //             $ip = (new Whip())->getValidIpAddress();
    //             $ipinfo = IpInfoUtils::info($ip);
    //             if ($ip && $ipinfo) {
    //                 if (isset($ipinfo['city']) && $ipinfo['city']) {
    //                     if(strpos($ipinfo['city'],'市') !== false) {
    //                         $ipinfo['city'] = substr($ipinfo['city'],0,strrpos($ipinfo['city'],'市'));
    //                     }
    //                     $this->params['offten_city'] = $this->params['city'] = $ipinfo['city'];
    //                 }
    //                 if (isset($ipinfo['province']) && $ipinfo['province']) {
    //                     if(strpos($ipinfo['province'],'省') !== false) {
    //                         $ipinfo['province'] = substr($ipinfo['province'],0,strrpos($ipinfo['province'],'省'));
    //                     }
    //                     $this->params['province'] = $ipinfo['province'];
    //                 }
    //                 if (!$this->params['offten_city']) {
    //                     unset($this->params['offten_city'], $this->params['city']);
    //                 }
    //                 if (!$this->params['province']) {
    //                     unset($this->params['province']);
    //                 }
    //             }
    //         } catch (\Exception $e) {
                
    //         }
    //     }

    //     if (isset($this->params['name']) && $this->params['name'] != $this->member['name']) {
    //         $nickExist = Db::name('user')->where(['name'=>$this->params['name'], 'reg'=>1])->count();
    //         if ($nickExist) {
    //             return $this->miss('昵称已被占用');
    //         }
    //     }

    //     if (isset($this->params['name']) && $this->params['name'] != $this->member['name'] && isset($config['check_edit_nickname']) && $config['check_edit_nickname'] == 1) {

    //         $limit = UserDeedLimit::check($this->member['id'], 3);
    //         if ($limit) {
    //             return $this->miss('当前已被限制修改昵称');
    //         }
    //         UserMaterialVerify::index(3, $this->member['id'], $this->params['name']);
    //         (new \app\service\TencentIM)->account_import($this->member['id'], $this->params['name'], $this->member['head_portrait']?:$this->member['head_100']);
    //         // unset($this->params['name']);
    //     }
    //     if (isset($this->params['slogan']) && $this->params['slogan'] && isset($config['check_edit_slogan']) && $config['check_edit_slogan'] == 1) {
    //         UserMaterialVerify::index(4, $this->member['id'], $this->params['slogan']);
    //         // unset($this->params['slogan']);
    //     }
    //     if (isset($this->params['self_slogan']) && $this->params['self_slogan'] && isset($config['check_edit_self_slogan']) && $config['check_edit_self_slogan'] == 1) {
    //         UserMaterialVerify::index(6, $this->member['id'], $this->params['self_slogan']);
    //         // unset($this->params['self_slogan']);
    //     }
    //     if (isset($this->params['cover']) && $this->params['cover'] && $this->params['cover'] != $this->member['cover']) {
    //         UserMaterialVerify::index(7, $this->member['id'], $this->params['cover']);
    //     }
    //     UserModel::update($this->params);
    //     if (sizeof($xuniEdit)) {
    //         Db::name('user')->where(['reg'=>2,'authcode'=>$this->member['id']])->update($xuniEdit);
    //     }
    //     // if ($clearConfigPrice) {
    //     //     Db::name('config_personal')->where(['user_id'=>$this->member['id']])->update(['chat_price'=>0,'voice_price'=>0,'video_price'=>0]);
    //     // }

    //     if (!$info) {
    //         // 任务
    //         Task::finish('info', $this->member['id']);
    //     }

    //     if (!$more_info) {
    //         // 任务
    //         Task::finish('more_info', $this->member['id']);
    //     }

    //     if (!$perfect_info) {
    //         // 任务
    //         Task::finish('perfect_info', $this->member['id']);
    //     }
    //     // UserProfile::change($this->member['id'], $this->params);
    //     return $this->pass($success_text);
    // }


    public function editInfo()
    {
        if (isset($this->params['bank_number'])) {
            $origin_result = $this->editBankcard();
            $result = $origin_result->getData();
            if ($result['code']!=200) return $origin_result;
        }
        $this->params['user_id'] = $this->params['user_id'] ?? $this->member['id'];
        //  $this->params['city'] = $this->params['offten_city'];
        $success_text = '修改成功';
        $config = Config::index('check');
        $contain = ['id', 'volley', 'score', 'password', 'sex', 'head_100', 'head_300', 'head_portrait'];
        // 基本资料
        $info = ['name', 'sex', 'birthday', 'city', 'stature', 'emotion', 'education_background', 'monthly_salary', 'occupation', 'slogan'];
        // 更多资料
        $more_info = ['school_of_graduation', 'weight', 'through_membership', 'live_status', 'is_house_purchase', 'is_car_purchase'];
        // 自我介绍
        $perfect_info = ['self_slogan'];

        $auths = [
            'education_background' => 'is_education_authentication',
            'is_car_purchase' => 'car_auth',
            'is_house_purchase' => 'house_auth',
            'monthly_salary' => 'income_auth',
            'emotion' => 'marry_auth',
        ];

        $xuniEdit = [];

        $minganci = Db::name('filter_word')->where(['state' => 1])->column('name');

        $infoFields = Db::getTableInfo('user', 'fields');


        $clearConfigPrice = false;
        foreach ($this->params as $key => $value) {
            if (in_array($key, $contain)) {
                unset($this->params[$key]);
            }
            if (!in_array($key, $infoFields) && !in_array($key, ['user_id', 'code'])) {
                unset($this->params[$key]);
            }

            if (in_array($key, $info)) {
                unset($info[array_search($key, $info)]);
            }

            if (in_array($key, array_keys($auths))) {
                $state = $this->member[$auths[$key]];
                if (in_array($state, [1,2])) {
                    unset($this->params[$key]);
                }
            }

            if (in_array($key, $more_info) && $value) {
                unset($more_info[array_search($key, $more_info)]);
            }

            if (in_array($key, $perfect_info) && $value) {
                unset($perfect_info[array_search($key, $perfect_info)]);
            }
            if ($key == 'birthday') {
                unset($this->params['self_slogan']);
                $changeagelimit = false;
                if ($this->member['age']) {
                    $changeagelimit = Db::name('change_age_limit')->where(['user_id'=>$this->member['id']])->find();
                }
                if($changeagelimit){
                    unset($this->params['birthday']);
                }else{
                    if ($value) {
                        $xuniEdit['age'] = $this->params['age'] = countage($value);

                        $idcardnumber = Db::name('user_certification')->where(['user_id'=>$this->member['id'], 'status'=>1])->value('data');
                        if ($idcardnumber) {
                            $age = countage(_getDateFromIdcard($idcardnumber));
                            if ($age) {
                                // if ($this->params['age'] > $age + 5 || $age - 5 > $this->params['age']) {
                                //     unset($this->params['age']);
                                //     unset($this->params['birthday']);
                                //     $success_text = '请填写真实的年龄，不得大于或者小于身份证年龄的5岁';
                                // }
                            }
                        }
                        if (isset($this->params['age']) && $this->member['age'] != $this->params['age']) {
                            $clearConfigPrice = true;
                        }
                    } else {
                        $this->params['birthday'] = '';
                    }
                }
            }

            if ($key == 'voice' && $value && $value != $this->member['voice']) {
                $result = Db::name('user_certification')->where(['types' => 5, 'user_id' => $this->member['id']])->find();
                if ($result) {
                    Db::name('user_certification')->where(['id' => $result['id']])->update(['image_front' => $value, 'status' => 0, 'reason' => '', 'update_time' => time()]);
                } else {
                    Db::name('user_certification')->insert([
                        'types' => 5,
                        'user_id' => $this->member['id'],
                        'image_front' => $value,
                        'create_time' => time(),
                        'update_time' => time()
                    ]);
                }

                $this->params['voice_auth'] = 1;
            }

            if(in_array($key, ['name', 'self_slogan', 'slogan'])){
                $keynames = ['name'=>'昵称','self_slogan'=>'自我介绍','slogan'=>'个性签名'];


                if(ishasPhoneNumber($value)){
                    exit(json_encode(['code' => 400, 'msg' => $keynames[$key] . '禁止输入手机号']));
                }


                foreach ($minganci as $v) {
                    if (stripos($value, $v) !== false) {
                        exit(json_encode(['code' => 400, 'msg' => $keynames[$key] . '含有敏感词"' . $v . '",请重新编辑']));
                    }
                }
                if ($key == 'name' && empty($value)) {
                    unset($this->params['name']);
                }
            }

            if (in_array($key, ['phone', 'paypwd'])) {
                if (!isset($this->params['code']) || !$this->params['code']) {
                    return $this->return['sms.error.code'];
                }

                // if (!isset($this->params['device_id']) || !$this->params['device_id']) {
                //     return $this->miss('设备错误');
                // }

                // if ($this->member['device_id'] != $this->params['device_id']) {
                //     return $this->miss('设备错误');
                // }

                $phone = $key == 'phone' ? $value : $this->member['phone'];

                $result = Code::verifyCode($phone, $this->params['code']);
                if ($result['code'] == 400) {
                    return $this->miss($result['msg']);
                }

                if ($key == 'paypwd') {
                    $this->params[$key] = password_hash($value, PASSWORD_DEFAULT);
                }

                unset($this->params['code']);
            }

            if ($key == 'occupation') {
                if ($value) {
                    $hasoccupation = Db::name('user_occupation')->where(['name'=>$value])->find();
                    if (!$hasoccupation) unset($this->params['occupation']);
                }
            }
        }

        $this->params['id'] = $this->params['user_id'];
        unset($this->params['user_id']);
        
        $this->params['city'] = $this->params['offten_city']??'';//修正app地址修改不成功的问题

        if (!isset($this->params['city'])) {
            try {
                $ip = (new Whip())->getValidIpAddress();
                $ipinfo = IpInfoUtils::info($ip);
                if ($ip && $ipinfo) {
                    if (isset($ipinfo['city']) && $ipinfo['city']) {
                        if(strpos($ipinfo['city'],'市') !== false) {
                            $ipinfo['city'] = substr($ipinfo['city'],0,strrpos($ipinfo['city'],'市'));
                        }
                        $this->params['offten_city'] = $this->params['city'] = $ipinfo['city'];
                    }
                    if (isset($ipinfo['province']) && $ipinfo['province']) {
                        if(strpos($ipinfo['province'],'省') !== false) {
                            $ipinfo['province'] = substr($ipinfo['province'],0,strrpos($ipinfo['province'],'省'));
                        }
                        $this->params['province'] = $ipinfo['province'];
                    }
                    if (!$this->params['offten_city']) {
                        unset($this->params['offten_city'], $this->params['city']);
                    }
                    if (!$this->params['province']) {
                        unset($this->params['province']);
                    }
                }
            } catch (\Exception $e) {
                
            }
        }
        
        

        if (isset($this->params['name']) && $this->params['name'] != $this->member['name']) {
            $nickExist = Db::name('user')->where(['name'=>$this->params['name'], 'reg'=>1])->count();
            if ($nickExist) {
                return $this->miss('昵称已被占用');
            }
        }

        if (isset($this->params['name']) && $this->params['name'] != $this->member['name'] && isset($config['check_edit_nickname']) && $config['check_edit_nickname'] == 1) {

            $limit = UserDeedLimit::check($this->member['id'], 3);
            if ($limit) {
                return $this->miss('当前已被限制修改昵称');
            }
            UserMaterialVerify::index(3, $this->member['id'], $this->params['name']);
            (new \app\service\TencentIM)->account_import($this->member['id'], $this->params['name'], $this->member['head_portrait']?:$this->member['head_100']);
            // unset($this->params['name']);
        }
        if (isset($this->params['slogan']) && $this->params['slogan'] && isset($config['check_edit_slogan']) && $config['check_edit_slogan'] == 1) {
            UserMaterialVerify::index(4, $this->member['id'], $this->params['slogan']);
            // unset($this->params['slogan']);
        }
        if (isset($this->params['self_slogan']) && $this->params['self_slogan'] && isset($config['check_edit_self_slogan']) && $config['check_edit_self_slogan'] == 1) {
            UserMaterialVerify::index(6, $this->member['id'], $this->params['self_slogan']);
            // unset($this->params['self_slogan']);
        }
        if (isset($this->params['cover']) && $this->params['cover'] && $this->params['cover'] != $this->member['cover']) {
            UserMaterialVerify::index(7, $this->member['id'], $this->params['cover']);
        }
        UserModel::update($this->params);
        if (sizeof($xuniEdit)) {
            Db::name('user')->where(['reg'=>2,'authcode'=>$this->member['id']])->update($xuniEdit);
        }
        // if ($clearConfigPrice) {
        //     Db::name('config_personal')->where(['user_id'=>$this->member['id']])->update(['chat_price'=>0,'voice_price'=>0,'video_price'=>0]);
        // }

        if (!$info) {
            // 任务
            Task::finish('info', $this->member['id']);
        }

        if (!$more_info) {
            // 任务
            Task::finish('more_info', $this->member['id']);
        }

        if (!$perfect_info) {
            // 任务
            Task::finish('perfect_info', $this->member['id']);
        }
        // UserProfile::change($this->member['id'], $this->params);
        return $this->pass($success_text);
    }
    private function set_auth($post = [])
    {
        // $this->member = Db::name('user')->find(11);
        // $post = input();
        $post = sizeof($post) ? $post : $this->params;
        $post['mobile_no'] = $this->member['phone'];
        $account_info = Db::name('adapay_user_account')->where(['user_id'=>$this->member['id']])->find();
        if (!$account_info) {
            try {
                $result = action('api/adapay/query_user', ['member_id'=>$this->member['id']]);
                $result = $result->getData();
                if ($result['code'] != 200) {
                    return $this->miss($result['msg']);
                }
                $account_info = [
                    'user_id'=>$this->member['id'],
                    'mobile_no'=>$post['mobile_no'],
                    'name'=>$post['bank_user_name'],
                    'cert_no'=>$post['cert_no'],
                    'card_no'=>$post['bank_number'],
                    'huifu_id'=>sizeof($result['data']['settle_accounts'])?$result['data']['settle_accounts'][0]['id']:0,
                    'create_time'=>datetime()
                ];
                $account_info['id'] = Db::name('adapay_user_account')->insertGetId($account_info);
                return $this->pass('设置成功');
            } catch (\Exception $e) {
                return $this->miss('请稍后再试'.$e->getMessage());        
            }
        } else {
            try {
                $result = action('api/adapay/query_user', ['member_id'=>$this->member['id']]);
                $result = $result->getData();
                if ($result['code'] != 200) {
                    return $this->miss($result['msg']);
                }
                $huifu_id = sizeof($result['data']['settle_accounts'])?$result['data']['settle_accounts'][0]['id']:0;
                $update = [
                    'mobile_no'=>$post['mobile_no'],
                    'name'=>$post['bank_user_name'],
                    'cert_no'=>$post['cert_no'],
                    'card_no'=>$post['bank_number'],
                    'huifu_id'=>$huifu_id,
                    'update_time'=>datetime()
                ];
                $res = Db::name('adapay_user_account')->where(['id'=>$account_info['id']])->update($update);
                return $this->pass('设置成功');
            } catch (\Exception $e) {
                return $this->miss('请稍后再试'.$e->getMessage());        
            }
        }
    }
    public function editBankcard()
    {
        $post = $this->params;
        // $this->member['id'] = 0;
        $account_info = Db::name('adapay_user_account')->where(['user_id'=>$this->member['id']])->find();
        $post['cert_no'] = Db::name('user_certification')->where(['types'=>1,'user_id'=>$this->member['id'], 'status'=>1])->value('data');
        if (!$post['cert_no']) {
            return $this->miss('请联系客服审核身份认证');
        }
        $param = [
            'card_id' => $post['bank_number'],
            'card_name' => $post['bank_user_name'],
            'cert_id' => $post['cert_no'],
            'cert_type' => '00',
            'tel_no' => $this->member['phone'],
            'bank_acct_type' => 2,
        ];

        try {
            $query_user = action('api/adapay/query_user', ['member_id'=>$this->member['id']]);
            $query_user = $query_user->getData();
            if ($query_user['code'] == 200) {
                $huifu_id = sizeof($query_user['data']['settle_accounts'])?$query_user['data']['settle_accounts'][0]['id']:0;
                if ($huifu_id) {
                    //action('api/adapay/delete_settle_account', ['member_id'=>$this->member['id'], 'settle_account_id'=>$huifu_id]);
                }
            }

            $result = action('api/adapay/set_settle_account', ['member_id'=>$this->member['id'], 'account_info'=>$param]);
            $result = $result->getData();
            if ($result['code'] != 200) {
                return $this->miss($result['msg']);
            }
            $this->set_auth($post);
            return $this->pass('设置成功');
        } catch (\Exception $e) {
            return $this->miss('请稍后再试'.$e->getMessage());        
        }
    }

    public function addBlackList()
    {
        $blackList = Blacklist::get([
            'user_id' => $this->params['user_id'],
            'to_user' => $this->params['to_user'],
        ]);
        
        Cache::rm('black' . $this->params['user_id'] . '_' . $this->params['to_user']);

        if ($blackList) {
            Blacklist::destroy($blackList->id);

            return $this->return['user.success.rmBlacklist'];
        } else {
            Blacklist::create([
                'user_id' => $this->params['user_id'],
                'to_user' => $this->params['to_user'],
            ]);

            return $this->return['user.success.blacklist'];
        }
    }

    public function blackList()
    {
        if(!isset($this->params['user_id'])){
            return $this->pass([]);
        }
        $uids = [$this->params['user_id']];
        $pri_uid = Db::name('user')->where(['reg'=>2,'authcode'=>$this->params['user_id']])->value('id');
        if ($pri_uid) {
            $uids[] = $pri_uid;
        }
        $data = Db::name('blacklist t1')
            ->field('t1.id, t2.id user_id, t2.head_300 user_head, t2.name user_name, t2.slogan user_slogan, t2.reg')
            ->join('user t2', 't2.id = t1.to_user')
            ->where(['user_id' => ['in', $uids]])
            ->order('id desc')->select();

        return $this->pass($data, 'result');
    }

    public function attention()
    {
        $attention = Attention::get([
            'user_id' => $this->params['user_id'],
            'to_user' => $this->params['to_user'],
        ]);
    
        Cache::rm('follow' . $this->params['user_id'] . '_' . $this->params['to_user']);

        if ($attention) {
            $friend = Attention::get(['user_id' => $this->params['to_user'], 'to_user' => $this->params['user_id'], 'sys_channel' => 1]);

            Attention::destroy($attention->id);
            UserModel::where(['id' => $this->params['to_user']])->setDec('attention');
            UserModel::where(['id' => $this->params['user_id']])->setDec('following');

            if ($friend) {
                UserModel::where(['id' => $this->params['to_user']])->setDec('friend');
                UserModel::where(['id' => $this->params['user_id']])->setDec('friend');
            }
            // $this->removeFriend($this->params['to_user']);

            return $this->return['user.success.rmAttention'];
        } else {
            Attention::create([
                'user_id' => $this->params['user_id'],
                'to_user' => $this->params['to_user'],
                'sys_channel' => 1
            ]);
            UserModel::where(['id' => $this->params['to_user']])->setInc('attention');
            UserModel::where(['id' => $this->params['user_id']])->setInc('following');

            $friend = Attention::get(['user_id' => $this->params['to_user'], 'to_user' => $this->params['user_id'], 'sys_channel' => 1]);
            if ($friend) {
                UserModel::where(['id' => $this->params['to_user']])->setInc('friend');
                UserModel::where(['id' => $this->params['user_id']])->setInc('friend');
            }


            $touserid = $this->params['to_user'];
            if ($touserid && $touserid != $this->member['id']) {
                $message = [
                    'type' => 1,
                    'to_user' => $touserid,
                    'context' => json_encode([
                                    'name' => $this->member['name'],
                                    'head' => $this->member['head_100']
                                ], JSON_UNESCAPED_UNICODE),
                    'uid' => $this->member['id'],
                    'user_id'=>$touserid
                ];

                Db::name('sys_message')->insert($message);


                $Gatewaymessage = json_encode([
                    "code" => 200,
                    "action" => 'api/Privatechat/interactionCount',
                    'data' => []
                ]);

                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $Gatewaymessage);
            }

            // 任务
            Task::finish('attention', $this->member['id'], $this->member['following'] + 1);

            return $this->return['user.success.attention'];
        }
    }

    public function removeFriend($touserid)
    {
        $str = $this->member['id'] . ',' . $touserid;
        $couple = $this->member['id'] > $touserid ? 'b' : 'a';

        $intimate = Db::name('user_intimate')->where(['couple_'. $couple => $str])->find();
        if (!$intimate) return '';

        if ($intimate['unshow'] == 3) return '';
        $state = $couple == 'a' ? 1 : 2;
        if ($intimate['unshow'] == $state) return '';

        if ($couple == 'a') {
            if ($intimate['unshow'] == 2) {
                $state = 3;
            }
        } else {
            if ($intimate['unshow'] == 1) {
                $state = 3;
            }
        }
        Db::name('user_intimate')->where(['id'=>$intimate['id']])->update(['unshow'=>$state]);
    }

    public function reportSelected()
    {
        $data = Db::name('report_selected')->where('is_hide', 0)->field('id, title value')->select();

        return $this->pass($data, 'result');
    }

    public function reportUser(Request $request = null)
    {
        $real_user_id = $this->member['id'];
        if ($this->member['reg']==2) {
            $real_user_id = $this->member['authcode'];
        }
        // $userData = Db::name('user_data')->where(['user_id'=>$real_user_id])->find();
        // if (!$userData || ($userData['consume'] == 0 && $userData['income'] == 0)) {
        //     return $this->return['common.success.submit'];
        // }
        // $selfpush = Db::name('chat_lists')->where(['user_id'=>$this->member['id'], 'another_id'=>$request->param('report_user')])->find();
        // $selfpull = Db::name('chat_lists')->where(['another_id'=>$this->member['id'], 'user_id'=>$request->param('report_user')])->find();
        // if(!$selfpush && !$selfpull){
        //     return $this->return['common.success.submit'];
        // }
        // if(($selfpush && $selfpush['user_first'] == 1) || ($selfpull && $selfpull['another_first'] == 1)){
        //     return $this->return['common.success.submit'];
        // }
        ReportUser::create([
            'user_id' => $request->param('user_id'),
            'user_hone' => $request->param('phone'),
            'report_desc' => $request->param('desc'),
            'report_type' => $request->param('type'),
            'report_selected_id' => $request->param('report_selected_id'),
            'report_user' => $request->param('report_user'),
            'optional_real_name' => $request->param('optional_real_name'),
            'optional_work_unit' => $request->param('optional_work_unit'),
            'optional_msn' => $request->param('optional_msn'),
            'optional_qq' => $request->param('optional_qq'),
            'optional_email' => $request->param('optional_email'),
            'optional_phone' => $request->param('optional_phone'),
            'optional_picture' => $request->param('optional_picture'),
            'time' => time()
        ]);

        // $report_selected = Db::name('report_selected')->where('id',$request->param('report_selected_id'))->find();
        $toUserSex = Db::name('user')->where('id',$request->param('report_user'))->value('sex');
        if($toUserSex == '女'){
            $touid = $request->param('report_user');
            $touserInfo = Db::name('user')->where('id',$touid)->find();
            if ($touserInfo && $touserInfo['reg']==2) {
                $touid = $touserInfo['authcode'];
            }

            UserPunish::inc($touid, 'complaint');
            $config = Config::where(['category' => 'kefu'])->cache(86400)->column('title, content');
            $kefu = intval($config['id']);
            $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk';
            $userInfo = Db::name('user')->where('id',$request->param('user_id'))->find();
            $datas = [
                'userid' => $kefu,
                'touserid' => $touid,
                'type' => 0,
                'content' => $userInfo['name'] . "（".$request->param('user_id')."）投诉你“". $request->param('desc') ."”，请及时处理纠纷，谢谢"
            ];
            curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));
        }

        return $this->return['common.success.submit'];
    }

    public function feedback()
    {
        $data = [
            'user_id' => $this->params['user_id'],
            'content' => $this->params['content']
        ];

        if (isset($this->params['img'])) {
            $data['images'] = $this->params['img'];
        }

        Feedback::create($data);

        return $this->return['common.success.submit'];
    }

    public function defend(Request $request = null)
    {
        $page = $request->param('page') ?: 1;
        $types = $request->param('types') ?: 1;

        if ($types == 1) {
            $field1 = 'to_user';
            $field2 = 'user_id';
        } else {
            $field1 = 'user_id';
            $field2 = 'to_user';
        }

        $data = Db::name('user_defend t1')
            ->field('t1.id, t1.' . $field1 . ' userid, t1.angel, t1.money, t1.update_time, t2.name, t2.head_100')
            ->join('user t2', 't2.id = t1.' . $field1)
            ->where([$field2 => $this->params['user_id']])
            ->order('money desc')
            ->page($page)->select();

        foreach ($data as $key => $item) {
            //$data[$key]['intimate'] = sprintf("%.1f", $item['money'] * 0.1);
            $data[$key]['intimate'] = sprintf("%.1f", $item['money']);
            $data[$key]['days'] = ceil((time() - $item['update_time']) / 86400);

            unset($data[$key]['money'], $data[$key]['update_time']);
        }

        return $this->pass($data);
    }

    public function volleyLists(Request $request = null)
    {
        $page = $request->param('page') ?: 1;
        $pagesize = $request->param('pagesize') ?: 10;

        $data = Db::name('volley_desc')
            ->field('id, content, price money, types, time')
            ->where(['user_id' => $this->member['id'], 'state' => 0])
            ->order('id desc')->page($page, $pagesize)->select();

        foreach ($data as $key => $item) {
            $num = stripos($item['content'], '付费。单号');

            if ($num) {
                $data[$key]['content'] = substr($item['content'], 0, $num);
            }

            $data[$key]['time'] = date('m-d H:i:s', $item['time']);
        }

        return $this->pass($data);
    }

    public function incomeLists(Request $request = null)
    {
        $page = $request->param('page') ?: 1;
        $pagesize = $request->param('pagesize') ?: 10;
        $types = $request->param('types') ?: 0;//0收入 1支出
        $cate = $request->param('cate') ?: 0;//聊天类型

        $whereTypes = ['礼物','视频','语音','消息','其他'];

        if($cate){
            if($cate == 4){
                $data = Db::name('yaoqing_records')
                    ->field('id, content, money, time, data types, order_id, show_money,balance')
                    ->where(['uid' => $this->member['id'], 'data' => $types])
                    ->where('content like "%'.$whereTypes[$cate - 1].'%" or content like "%聊天%"')
                    ->order('id desc')->page($page, $pagesize)->select();
            }elseif($cate < 5){
                $data = Db::name('yaoqing_records')
                    ->field('id, content, money, time, data types, order_id, show_money,balance')
                    ->where(['uid' => $this->member['id'], 'data' => $types])
                    ->where('content','like','%'.$whereTypes[$cate - 1].'%')
                    ->order('id desc')->page($page, $pagesize)->select();
            }else{
                $wherenotlike = [];
                for ($i=0; $i < 4; $i++) { 
                    $wherenotlike[] = 'content not like "%'.$whereTypes[$i].'%"';
                }
                $wherenotlike[] = 'content not like "%聊天%"';
                $data = Db::name('yaoqing_records')
                    ->field('id, content, money, time, data types, order_id, show_money,balance')
                    ->where(['uid' => $this->member['id'], 'data' => $types])
                    ->where(implode(' and ', $wherenotlike))
                    ->order('id desc')->page($page, $pagesize)->select();
            }
        }else{
            $data = Db::name('yaoqing_records')
                ->field('id, content, money, time, data types, order_id, show_money,balance')
                ->where(['uid' => $this->member['id'], 'data' => $types])
                ->order('id desc')->page($page, $pagesize)->select();
        }


        foreach ($data as $key => $item) {
            $data[$key]['time'] = date('m-d H:i:s', $item['time']);
            $data[$key]['money'] = $item['show_money'] != 0 ? $item['show_money'] : $item['money'];
            
            $data[$key]['money'] = $data[$key]['money']. '积分';
            $data[$key]['balance'] = '余额：'.$data[$key]['balance']. '积分';
            // 过滤手续费信息
            $data[$key]['content'] = preg_replace('/\s*\(手续费：\d+\)/', '', $item['content']);

            if(stripos($item['content'], '语音通话收益') !== false || stripos($item['content'], '视频通话收益') !== false && $item['order_id']){
                $tmp = Db::name('order_common')->cache(60)->find($item['order_id']);
                if($tmp){
                    $tmpdata = json_decode($tmp['data'], true);
                    $data[$key]['content'] .= ' ' . ($tmpdata['duration']?:1) . '分钟';
                }
            }
            unset($data[$key]['order_id']);
            unset($data[$key]['show_money']);
        }

        return $this->pass($data);
    }

    public function beauty()
    {
        
        $user = UserModel::get($this->member['id']);

        if (!$user['beauty']) {
            $original = BeautyImage::where(['is_hidden' => 0])->order('sort desc, id asc')->find();

            $data = [0, 0, 0, 0, $original];
        } else {
            $data = explode(',', $user['beauty']);

            $image = BeautyImage::get($data[4]);

            $data[4] = $image;
        }

        return $this->pass($data);
    }

    public function beautyImages()
    {
        $data = BeautyImage::all(function ($query) {
            $query->where(['is_hidden' => 0])->order('sort desc, id asc')->cache(86400);
        });

        return $this->pass($data);
    }

    public function voiceLike()
    {
        $user = UserModel::get($this->params['to_user']);

        if (!$user['voice']) return $this->return['like.error.notExist'];

        $userZan = UserZan::get([
            'types' => 2,
            'user_id' => $this->member['id'],
            'to_user' => $this->params['to_user'],
        ]);

        if ($userZan) {
            return $this->return['like.error.exist'];
        } else {
            UserZan::create([
                'types' => 2,
                'user_id' => $this->member['id'],
                'to_user' => $this->params['to_user'],
                'create_time' => time()
            ]);

            $count = UserZan::where(['types' => 2, 'user_id' => $this->member['id']])->count();
            // 任务
            Task::finish('like', $this->member['id'], $count);

            UserModel::update([
                'id' => $this->params['to_user'],
                'charm_value' => $user['charm_value'] + 1,
                'voice_zan' => $user['voice_zan'] + 1,
            ]);

            // 榜单记录
            //RankingRecords::index(6, $this->params['to_user'], $this->member['id'], 1);

            /*$notice = '恭喜！您的魅力吸引了' . $this->member['name'] . '的关注，Ta给您的语音签名点赞啦！';
            Privatechat::notice($this->params['to_user'], $notice);*/
    
            Cache::rm('zan' . $this->member['id'] . '_' . $this->params['to_user']);

            return $this->return['user.success.like'];
        }
    }

    public function tagsList()
    {
        $types = $this->member['sex'] == '男' ? 1 : 2;

        $data = Db::name('tags')
            ->field('id, name, user_id')
            ->where(['user_id' => $this->member['id']])
            ->whereOr(function ($query) use ($types) {
                $query->name('tags')->where(['types' => $types, 'user_id' => 0]);
            })->order('user_id desc, sort desc, id desc')->select();

        $selected = explode(',', $this->member['tags']);

        foreach ($data as $key => $item) {
            $data[$key]['selected'] = in_array($item['id'], $selected) ? 1 : 0;
        }

        return $this->pass($data);
    }

    public function createTag()
    {
        return $this->return['user.success.create'];

        $types = $this->member['sex'] == '男' ? 1 : 2;

        $id = Db::name('tags')->insertGetId(['types' => $types, 'user_id' => $this->member['id'], 'name' => $this->params['name']]);

        if ($this->member['tags']) {
            $tags = $this->member['tags'] . ',' . $id;
        } else {
            $tags = $id;
        }

        Db::name('user')->where(['id' => $this->member['id']])->setField('tags', $tags);

        // 任务
        Task::finish('tags', $this->member['id']);

        //return $this->return['user.success.create'];

        return $this->pass($id);
    }

    public function updateTags()
    {
        /*$tags = $this->params['tags'] ?? '';

        $tags = explode(',', trim($tags));

        if (count($tags) > 10) return $this->miss('最多可添加10个标签');

        Db::name('user')->where(['id' => $this->member['id']])->setField('tags', $this->params['tags']);

        if ($tags) {
            Db::name('tags')->where(['id' => ['not in', $tags], 'user_id' => $this->member['id']])->delete();
        } else {
            Db::name('tags')->where(['user_id' => $this->member['id']])->delete();
        }

        // 任务
        Task::finish('tags', $this->member['id']);*/

        return $this->return['common.success.update'];
    }

    public function bindInvite()
    {
        //return $this->miss('如需填写请联系客服');
        if ($this->member['yqr']) {
            return $this->miss('已有邀请人');
        }

        //$code = mb_strtoupper($this->params['invite_code']);
        $code = $this->params['invite_code'];

        $parent = Db::name('user')->where(['yqm' => $code, 'delete_time' => 0])->find();

        if (!$parent) {
            return $this->miss('邀请人不存在');
        }

        if ($parent['id'] == $this->member['id']) {
            return $this->miss('不能绑定自己为邀请人');
        }

        if ($this->member['yqm'] && $parent['yqr'] == $this->member['yqm']) {
            return $this->miss('不能绑定下级为邀请人');
        }

        //Db::name('user')->where(['id' => $this->member['id']])->setField('yqr', $code);
        Db::name('user')->where(['id' => $this->member['id']])->update(['yqr' => $code, 'invite_time' => time()]);

        // 邀请奖励
        /*Db::name('ranking_records')->insert([
            'types' => 8,
            'user_id' => $parent['id'],
            'to_user' => $this->member['id'],
            'count' => 1,
            'create_time' => time()
        ]);*/

        Db::name('user')->where(['id' => $parent['id']])->setInc('invite_count');

        //Db::name('user')->where(['id' => $this->member['id']])->setField('invite_time', time());

        $config = Config::index('invite');

        if (intval($config['bind_invite'])) {
            //Balance::index($this->member['id'], $config['bind_invite'], '绑定邀请人奖励', 1);
        }

        /*// 任务
        Task::finish('invite', $parent['id']);

        if ($parent['proxy'] + 0) {

            $hongbao = $config['hongbao'];

            $hongbao = explode(',',$hongbao);

            $hongbao[1] = $hongbao[1] ?? $hongbao[0];

            $money = mt_rand($hongbao[0],$hongbao[1]);

            if ($money + 0) {
                Income::index($parent['id'], $this->member['id'], $money, '邀请奖励收益', 1);
            }
        }*/
        UserModel::bindParent_new($parent['id'], $this->member['id'], 2,0,1,'APP主动绑定');
        RegModel::parentSay($this->member['id'], $this->member['sex'], '', $parent);

        return $this->pass('绑定邀请人成功');
    }
    
    public function checkFate(Request $request = null)
    {
        $cachekey = 'checkFate' . $this->member['id'];
        $num = cache($cachekey);
        if ($num) {
            return $this->miss('点击频繁');
        }
        $num = $num ? ++$num : 1;
        cache($cachekey, $num, 2);

        $user_id = $request->param('user_id');

        // 修改1：增加查询sex字段
        $user = Db::name('user')->field('zhaohu_time, sex')->where(['id' => $user_id])->find();

        if (!$user) {
            return $this->miss('用户不存在');
        }

        $config = Config::where(['category' => ['in', ['kefu', 'sayhi']]])->cache(86400)->column('title, content');
        $kefu = intval($config['id']);

        $zhaohu = 0;
        $msg = 'success';
        if ($user_id != $kefu) {
            // 修改2：添加性别判断逻辑
            $isFemale = $user['sex'] == '女';

            if ($isFemale) {
                // 女性用户跳过时间检查，直接进入功能开关判断
                $configPersonal = Db::name('config_personal')->where(['user_id' => $user_id])->find();

                if (isset($configPersonal['fate_limit']) && ($configPersonal['fate_limit'] + 0)) {
                    $msg = '今日缘分功能已关闭';
                } else {
                    if (isset($configPersonal['fate_switch']) && ($configPersonal['fate_switch'] + 0)) {
                        $zhaohu = 1;
                    } else {
                        $msg = '请打开设置>隐私设置>推送用户';
                    }
                }
            } else {
                // 非女性用户保持原有时长检查
                if (($user['zhaohu_time'] + $config['sayhi_times']) < time()) {
                    $configPersonal = Db::name('config_personal')->where(['user_id' => $user_id])->find();

                    if (isset($configPersonal['fate_limit']) && ($configPersonal['fate_limit'] + 0)) {
                        $msg = '今日缘分功能已关闭';
                    } else {
                        if (isset($configPersonal['fate_switch']) && ($configPersonal['fate_switch'] + 0)) {
                            $zhaohu = 1;
                        } else {
                            $msg = '请打开设置>隐私设置>推送用户';
                        }
                    }
                } else {
                    $msg = '未到时间';
                }
            }
        } else {
            $msg = '客服账号未开启此功能';
        }

        if ($zhaohu) {
            // 修改3：无论男女用户，打招呼成功后都更新时间戳
            Db::name('user')->where('id', $user_id)->update(['zhaohu_time' => time()]);
            return $this->pass(['zhaohu' => $zhaohu]);
        } else {
            return $this->miss($msg);
        }
    }
    
    public function checkFate_back0523(Request $request = null)
    {

        $cachekey = 'checkFate' . $this->member['id'];
        $num      = cache($cachekey);
        if ($num) {
            return $this->miss('点击频繁');
        }
        $num = $num ? ++$num : 1;
        cache($cachekey, $num, 2);

        $user_id = $request->param('user_id');
        
        $user = Db::name('user')->field('zhaohu_time')->where(['id' => $user_id])->find();
        
        $config = Config::where(['category' => ['in', ['kefu', 'sayhi']]])->cache(86400)->column('title, content');
        $kefu = intval($config['id']);
        
        $zhaohu = 0;
        $msg = 'success';
        if ($user_id != $kefu) {
            if (($user['zhaohu_time'] + $config['sayhi_times']) < time()) {
                
                $configPersonal = Db::name('config_personal')->where(['user_id' => $user_id])->find();
    
                if (isset($configPersonal['fate_limit']) && ($configPersonal['fate_limit'] + 0)) {
                    $msg = '今日缘分功能已关闭';
                } else {
                    if (isset($configPersonal['fate_switch']) && ($configPersonal['fate_switch'] + 0)) {
                        $zhaohu = 1;
                    } else {
                        $msg = '请打开设置>隐私设置>推送用户';
                    }
                }
            } else {
                $msg = '未到时间';
            }
        } else {
            $msg = '客服账号未开启此功能';
        }
        
        if ($zhaohu) {
            return $this->pass(['zhaohu' => $zhaohu]);
        } else {
            return $this->miss($msg);
        }
    }


    public function setstate($user_id = 0){
        $state = input('state/d',0);
        // if (!$user_id) return $this->pass('');
        // Db::name('user')->where(['id'=>(int)$user_id, 'reg'=>1])->update(['unpush'=>$state]);
        $this->pass('');
    }
    public function bindwx(Request $request = null){
        $user_id = $this->member['id'];
        $wechat = $request->param('wechat');
        $wechat_name = $request->param('wechat_name');
        $zhifuname = $request->param('zhifuname');
        if(!$zhifuname){
            return $this->miss('请填写真实姓名');
        }
        $realname = Db::name('user_certification')->where(['types' => 1, 'user_id' => $user_id])->value('data2');
        $realname = $realname ? trim($realname) : '';
        if($realname){
            if ($realname != $zhifuname) {
                exit(json_encode(['code' => 201, 'msg' => '提现账户姓名需与实名信息姓名一致'], JSON_UNESCAPED_UNICODE));
            }
        }
        $user = Db::name('user')->where(['id'=>$user_id])->find();
        if($user['wechat'] && $user['wechat'] != $wechat){
            return $this->miss('当前已绑定微信，如需更换请联系客服');
        }
        $user = Db::name('user')->where(['wechat'=>$wechat])->find();
        if($user && $user['id'] != $user_id){
            return $this->miss('当前微信已绑定其他账号');
        }
        Db::name('user')->where(['id'=>$user_id])->update(['wechat'=>$wechat, 'wechat_name'=>$wechat_name, 'zhifuname'=>$zhifuname]);
        return $this->pass('绑定成功');
    }
    public function code($user_id = 0)
    {
        $code = Db::name('user')->where(['id'=>$user_id])->value('yqm');
        return $code ? $this->pass($code) : $this->miss('获取失败');
    }
    public function changeRole(){
        $user_id = $this->member['id'];
        $role = input('role/d', 0);
        $role_child = input('role_child/s', '');
        $entertainment = $this->member['entertainment'];
        if ($this->member['sex'] == '女' && $entertainment == 2) return $this->miss('当前不允许切换到其他角色');
        $role = Db::name('user_entertainment')->where(['id'=>$role+1])->value('role_type');
        if (!in_array($role, [0, 1, 2, 3])) return $this->miss('操作失败');
        if ($this->member['entertainment'] == $role && $this->member['entertainment_child'] == $role_child) return $this->pass('操作成功');
        if ($role_child) {
            $additionValue = 1;
            $numbersArray = explode(',', $role_child);
            if (sizeof($numbersArray)>1 && $role!=0) {
                return $this->miss('仅娱乐类型可选多种下级类型');
            }
            $resultArray = array_map(function ($number) use ($additionValue) {
                return $number + $additionValue;
            }, $numbersArray);
            $resultString = implode(',', $resultArray);

            $parents = Db::name('user_entertainment')->where(['id'=>['in',$resultString]])->column('parent_id','id');
            $role_child = [];
            foreach ($parents as $key => $value) {
                if ($value != $role + 1) continue;
                $role_child[] = $key - 1;
            }
            $role_child = implode(',', $role_child);
        }
        $res = Db::name('user')->where(['id'=>$user_id])->update([
            'entertainment'=>$role,
            'entertainment_child'=>$role_child
        ]);
        if ($res) {
            if (in_array($role, [2,3]) && !in_array($entertainment, [2,3])) {
                $userConfigPrice = Db::name('config_personal')->where(['user_id'=>$this->member['id']])->find();
                if ($userConfigPrice) {
                    Db::name('config_personal')->where(['user_id'=>$this->member['id']])->update([
                        'chat_price'=>$userConfigPrice['chat_price'] * 0.2,
                        'voice_price'=>$userConfigPrice['voice_price'] * 0.2,
                        'video_price'=>$userConfigPrice['video_price'] * 0.2,
                    ]);
                }
                if ($this->member['sex'] == '女') {
                    if ($role == 2) {
                        Privatechat::notice($user_id, '你选择了交友身份（真实交友），只能设置比较低的聊天价格，如果选择错了可以联系客服更改');
                    } else if ($role == 3) {
                        Privatechat::notice($user_id, '你选择了找对象使用目的，只能设置很低的聊天价格或者不设置，如果选择有误可以修改使用目的');
                    }
                }
            } else if (!in_array($role, [2,3]) && in_array($entertainment, [2,3])) {
                $userConfigPrice = Db::name('config_personal')->where(['user_id'=>$this->member['id']])->find();
                if ($userConfigPrice) {
                    Db::name('config_personal')->where(['user_id'=>$this->member['id']])->update([
                        'chat_price'=>$userConfigPrice['chat_price'] / 0.2,
                        'voice_price'=>$userConfigPrice['voice_price'] / 0.2,
                        'video_price'=>$userConfigPrice['video_price'] / 0.2,
                    ]);
                }
            }
            Db::name('user')->where(['authcode'=>$user_id, 'reg'=>2])->update([
                'entertainment'=>$role,
                'entertainment_child'=>$role_child
            ]);
            $this->recordEntertainment($role, $role_child);
            return $this->pass('操作成功');
        }
        return $this->miss('操作失败');
    }

    private function recordEntertainment($role='',$role_child='')
    {
        $roles = explode(',', $role);
        if ($role_child) {
            $roles = array_unique(array_merge($roles,explode(',', $role_child)));
        }
        $userHasRoles = Db::name('user_entertainment_checked')->where(['user_id'=>$this->member['id']])->column('id','entertainment_map');
        $inserts = [];
        $deletes = [];
        foreach ($roles as $value) {
            if (isset($userHasRoles[$value])) continue;
            $inserts[] = [
                'user_id'=>$this->member['id'],
                'entertainment_map'=>$value
            ];
        }
        foreach ($userHasRoles as $key => $value) {
            if (in_array($key, $roles)) continue;
            $deletes[] = $value;
        }
        if (sizeof($inserts)) {
            Db::name('user_entertainment_checked')->insertAll($inserts);
        }

        if (sizeof($deletes)) {
            Db::name('user_entertainment_checked')->delete($deletes);
        }
    }

    public function getUserEntertainment($touserid = '')
    {
        $entertainment = Db::name('user')->where(['id'=>$touserid])->value('entertainment');
        return $this->pass(compact('entertainment'));
    }
    public function getUserYqr()
    {
        $prev_time = time() - 1800;
        $whip = new Whip();
        $clientAddress = $whip->getValidIpAddress();
        $s1 = Db::name('proxy_visit_records')->where(['ip' => $clientAddress, 'create_time' => ['gt', $prev_time]])->order('create_time desc')->value('user_id');
        $yqm = '';
        if ($s1) {
            $s1_yqm = Db::name('user')->where(['id' => $s1])->value('yqm');
            if ($s1_yqm) {
                $yqm = $s1_yqm;
            }
        }
        return $this->pass(compact('yqm'));
    }

    public function bind()
    {
        $touserid = input('touserid/d', 0);
        $remark = input('remark/s', '');
        $video = input('video/s', '');
        $cover = input('cover/s', '');
        $images = input('images/s', '');

        if ($touserid == $this->member['id']) return $this->miss('不能绑定自己');
        if (!$touserid || (!$video && !$images)) return $this->miss('请补充内容');

        $user = db('user')->where(['id'=>$touserid, 'reg'=>1, 'delete_time'=>0])->find();
        if (!$user || $user['yqr']) return $this->miss('用户不存在或已被绑定');

        if ($this->member['yqr']) {
            $yqms = [$user['yqm']];
            for ($i=0; $i < 10; $i++) { 
                if (in_array($this->member['yqr'], $yqms)) return $this->miss('不能绑定当前用户');
                $yqm = db('user')->where(['yqr'=>['in', $yqms]])->column('yqm');
                if (empty($yqm)) break;
                $yqms = array_merge($yqms, $yqm);
            }
        }

        $where = ['touserid'=>$touserid, 'state'=>0];
        $has = db('user_invite_apply')->where($where)->find();
        if ($has) {
            if($has['user_id'] == $this->member['id']) return $this->miss('你已提交申请绑定,请勿重复提交');
            return $this->miss('当前用户已被其他人申请绑定,请稍后再试');
        }

        $where['user_id'] = $this->member['id'];
        $where['remark'] = $remark;
        $where['video'] = $video;
        $where['cover'] = $cover;
        $where['images'] = $images;
        $where['create_time'] = time();

        $res = db('user_invite_apply')->insert($where);
        return $res ? $this->pass('提交申请成功') : $this->miss('提交失败,请稍后再试');
    }

    public function bind_records()
    {
        $page = input('page/d', 1);
        $pagesize = input('pagesize/d', 20);

        $data = db('user_invite_apply')
            ->where(['user_id'=>$this->member['id']])
            ->page($page)
            ->limit($pagesize)
            ->field('shenhe_admin_id', 'filter')
            ->order('id desc')
            ->select();

        foreach ($data as &$value) {
            $value['create_time'] = date('Y-m-d H:i', $value['create_time']);
            $value['shenhe_time'] = $value['shenhe_time'] ? date('Y-m-d H:i', $value['shenhe_time']) : '';
        }

        return $this->pass($data);
    }
    
    //用于批量修改用户的明文密码
    public function modifyOldPwd($opt)
    {
        set_time_limit(0);
        if ($opt == 1) {
            // 禁用输出缓冲
            ob_end_clean();
            header('Content-Type: text/html; charset=utf-8');
            header('X-Accel-Buffering: no'); // 针对Nginx服务器
            // 输出HTML框架
            echo '<html><head><meta charset="utf-8"><title>密码更新进度</title></head><body>';
            echo '<h3>正在处理用户密码更新...</h3>';
            echo '<div id="progress">';
            $pageSize = 100;
            $page = 1;
            $totalUpdated = 0;
            $totalProcessed = 0;
            do {
                $users = UserModel::where("(phone is not null and phone!='') and (password is not null and password!='') and register_datetime>'2025-01-01 00:00:00'")
                    ->order('id desc')
                    ->field('id,password')
                    ->page($page, $pageSize)
                    ->select();
                if (empty($users)) {
                    break;
                }
                $batchUpdated = 0;
                $totalProcessed += count($users);
                foreach ($users as $user) {
                    $userid = (int) ($user['id'] ?? $user->id);
                    $pwd = $user['password'] ?? $user->password;
                    if (!UserModel::looksLikeHash($pwd)) {
                        $hashedPassword = UserModel::encryptPassword($pwd);
                        $result = UserModel::where('id', $userid)->update(['password' => $hashedPassword]);
                        if ($result !== false) {
                            $batchUpdated++;
                        }
                    }
                }
                $totalUpdated += $batchUpdated;
                $page++;
                // 输出进度信息
                $progressHtml = sprintf(
                    '<p>批次 %d 处理完成：共 %d 条，更新 %d 条</p>',
                    $page - 1,
                    $totalProcessed,
                    $batchUpdated
                );
                echo $progressHtml;
                flush(); // 强制发送输出
            } while (true);
            // 输出最终结果
            $resultHtml = sprintf(
                '<h4>全部处理完成：共 %d 条记录，成功更新 %d 条</h4>',
                $totalProcessed,
                $totalUpdated
            );
            echo $resultHtml;
            echo '</div></body></html>';
            return ''; // 返回空字符串，避免与输出冲突
        } else {
            return '请传递操作值1';
        }
    }
    
    /**
	 * 用于更新动态的观看权限和评论权限  观看权限：男的看女的  女的看男的 评论权限：均可
	 *
	 * @param $opt 1表示执行此函数操作
	 * @return int|false  int表示成功执行的数据条数 bool false执行异常
	 */
	public function dymanicUp($opt)
	{
		if($opt!=1){
			return '请传递操作值1';
		}
		$result=Db::name('dymanic d')
			->join('user u', 'd.userid = u.id')  // 默认INNER JOIN
				->where('1=1')
			->update([
				'see_limit' => Db::raw("CASE 
			WHEN u.sex = '男' THEN 1  -- 男用户发布的动态，女可看
			WHEN u.sex = '女' THEN 2  -- 女用户发布的动态，男可看
			ELSE 0                   -- 其他情况未开放
		END"),
				'ping_limit' => Db::raw("CASE 
			WHEN u.sex = '男' THEN 3  -- 男用户发布的动态，均可评
			WHEN u.sex = '女' THEN 3  -- 女用户发布的动态，均可评
			ELSE 0                   -- 其他情况未开放
		END")
			]);
		if ($result !== false) {
			echo "成功更新 {$result} 条记录";
		} else {
			echo "更新失败";
		}
	}
	//APP端提现列表
    //APP端提现列表
    public function withdrawLists(Request $request = null)
    {
        $page = $request->param('page') ?: 1;
        $pagesize = $request->param('pagesize') ?: 10;
        $userid = $request->param('userid') ?: 0;
        $start = $request->param('start') ?: 0;
        $end = $request->param('end') ?: 0;
        if (!$userid) {
            return $this->miss('userid必传！');
        }
        // 构建查询条件
        $map = [];
        if ($start || $end) {
            if ($start) {
                $map[] = ['t1.create_time', '>=', strtotime($start)];
            }
            if ($end) {
                $map[] = ['t1.create_time', '<=', strtotime($end)];
            }
        }
        $data = Db::name('withdraw t1')
            ->master()
            ->field('t1.id,t1.userid,t2.name,t1.price,t1.shouxu,t1.paymethod,t1.create_time,t1.state,t1.status,t1.txstate,t1.update_time')
            ->join('user t2', 't2.id = t1.userid', 'left')
            ->where('t1.userid', $userid)
            ->where($map)
            ->order('t1.id desc')
            ->page($page, $pagesize)  // 关键分页方法
            ->select();
        foreach ($data as $k => $v) {
            //提现方式
            $paymethod=$v['paymethod'];
            if($paymethod==0){
                $data[$k]['paymethod']='微信提现';
            }elseif($paymethod==1){
                $data[$k]['paymethod']='支付宝提现';
            }elseif($paymethod==2){
                $data[$k]['paymethod']='银行卡提现';
            }
            //审核状态 提现状态
            $state=$v['state'];
            if($state==0){
                $data[$k]['stateshu']='审核中';
                $data[$k]['txstateshu']='进行中';
            }elseif($state==1){
                $data[$k]['stateshu']='通过';
                //判断是否提现成功
                if($v['txstate']==1){
                    $data[$k]['txstateshu']='成功';
                }elseif($v['txstate']==0){
                    $data[$k]['txstateshu']='进行中';
                }elseif($v['txstate']==2){
                    $data[$k]['txstateshu']='失败';
                }
            }elseif($state==2){
                $data[$k]['stateshu']='驳回';
                $data[$k]['txstateshu']='失败';
            }
            $data[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            unset($data[$k]['update_time']);
            unset($data[$k]['status']);
        }
        return $this->pass($data);
    }
}
